我'm a C newbie. I'使用http://www.binarytides.com/programming-udp-sockets-c-linux/中的代码编写一个简单的UDP echo服务器和客户端

它完美地运作 . 但是,我已决定添加动态解析服务器名称的代码,并在用户指定的端口上打开 . 我的客户端似乎挂在了gets()请求上 . 我究竟做错了什么?除了硬编码的IP和端口号之外,原始客户端工作正常 .

相关代码如下

int main(int argc, char *argv[]) {
int sockfd, rv, i;
char buf[BUFLEN];
char message[BUFLEN];
struct addrinfo hints, *servinfo, *p;
socklen_t fromlen;

if (argc != 3) {
    fprintf(stderr, "usage: %s hostname port\n", argv[0]);
    exit(1);
}

memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;

if ((rv = getaddrinfo(argv[1], argv[2], &hints, &servinfo)) != 0) {
    die("getaddrinfo");
}

// loop through all the results and connect to the first we can
for (p = servinfo; p != NULL; p = p->ai_next) {
    if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
        perror("client: socket");
        continue;
    }
    break;
}

if (p == NULL)
        die("client: failed to connect");

while (1) {
    printf("Enter message : ");
    gets(message);

    //send the message
    if (sendto(sockfd, message, strlen(message), 0, p->ai_addr, p->ai_addrlen) == -1)
        die("sendto()");        

    //receive a reply and print it
    //clear the buffer by filling null, it might have previously received data
    memset(buf, '\0', BUFLEN);

    fromlen = p->ai_addrlen;
    printf("Size is %d", fromlen);
    //try to receive some data, this is a blocking call
    if (recvfrom(sockfd, buf, BUFLEN, 0, p->ai_addr, &fromlen) == -1)
        die("recvfrom()");      

    puts(buf);
}

close(sockfd);
return 0;

有效的代码如下所示 . 它使用相同的gets()调用

int main(void)
{
    struct sockaddr_in si_other;
    int s, i, slen=sizeof(si_other);
    char buf[BUFLEN];
    char message[BUFLEN];


if ( (s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
{
    die("socket");
}

memset((char *) &si_other, 0, sizeof(si_other));
si_other.sin_family = AF_INET;
si_other.sin_port = htons(PORT);

if (inet_aton(SERVER , &si_other.sin_addr) == 0)
{
    fprintf(stderr, "inet_aton() failed\n");
    exit(1);
}

while(1)
{
    printf("Enter message : ");
    gets(message);

    //send the message
    if (sendto(s, message, strlen(message) , 0 , (struct sockaddr *) &si_other, slen)==-1)
    {
        die("sendto()");
    }

    //receive a reply and print it
    //clear the buffer by filling null, it might have previously received data
    memset(buf,'\0', BUFLEN);
    //try to receive some data, this is a blocking call
    if (recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen) == -1)
    {
        die("recvfrom()");
    }

    puts(buf);
}

close(s);
return 0;

}