我想知道此代码是否可以用于在Linux中从GPRS套接字接受数据。如果不是,则如何修改程序以与GPRS套接字通信。

server.c:

#define sport 5000
#define bufferlength 100

int main(int argc, char **argv[])
{
  struct sockaddr_in serveraddr;
  int sd, acceptsd, rc;
  char buffer[bufferlength];
  if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
  {
    perror("error in socket creation\n");
    exit(0);
  }
  else
    printf("socket is created\n");

  serveraddr.sin_family = AF_INET;
  serveraddr.sin_port = htons(sport);
  serveraddr.sin_addr.s_addr = (INADDR_ANY);
  //serveraddr.sin_addr.s_addr=inet_addr("127.0.0.1");
  rc = bind(sd, (struct sockaddr *) &serveraddr, sizeof(serveraddr));
  if (rc < 0)
  {
    perror("srver bind error\n");
    close(sd);
    exit(-1);
  }
  else
    printf("binding done\n");

  rc = listen(sd, 5);
  if (rc < 0)
  {
    perror("listen error");
    close(sd);
    exit(-1);
  }
  else
    printf("listen() is o.k.\n");

  printf("server is ready\n");

  wait(100);
  acceptsd = accept(sd, NULL, NULL);
  if (acceptsd < 0)
  {
    perror("error in accepting\n");
    exit(-1);
    close(sd);
  }
  else
    printf("connection accepted\n");

  printf("server is ready to accept data\n");
  rc = recv(acceptsd, buffer, sizeof(buffer), 0);
  if (rc < 0)
  {
    perror("error in recieving\n");
    close(acceptsd);
    close(sd);
    exit(-1);
  }

  printf("send() is`enter code here` ok\n");

  close(acceptsd);
  close(sd);

  exit(0);
}

最佳答案

如果你愿意


添加了丢失的#include语句,并
更正了main()的签名并
不会等待任何进程在调用accept()之前结束


该代码将接受一个连接的TCP客户端并接收至少一个字节,然后结束。

09-05 12:03