2 qq 28396927 qq_28396927 于 2015.07.10 21:49 提问

网络编程 inet_pton函数

在下面的函数出现了错误,编译的时候函数inet_pton函数出错,但是不知到原因,难道这个函数的用法错了吗

 #include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<stdio.h>
#include<stdlib.h>
#include<strings.h>
void outputError(char *message)
{
    fprintf(stdout, "error:%s\n",message);
    exit(0);
}

int main(int argc, char *argv[])
{

    int sockFd;
    char receiveBuffer;
    struct sockaddr_in server_addr;
    int port=13;
    if(argc!=2)
    {
    outputError("usage:getTime <IPaddress>");
    }
    if((sockFd=socket(AF_INET, SOCK_STREAM, 0))<0)
    {
    outputError("socket occured error!");
    }
    bzero(&server_addr, sizeof(server_addr));
    server_addr.sin_family=AF_INET;
    server_addr.sin_port=htonl(port);
    if((inet_pton(AF_INET, argv[1], &server_addr.sin_addr))<=0);
    {
    outputError("inet_pton occured error!");
    }
    if(connect(sockFd, (struct sockaddr*)&server_addr, sizeof(server_addr)<0));
    {
        outputError("connect to server failied");
    }
    while((read(sockFd, receiveBuffer, 1))==1)
    {
    fprintf(stdout, "%c", receiveBuffer);
    }
    exit(0);
}
```![图片说明](http://img.ask.csdn.net/upload/201507/10/1436536128_266268.png)

6个回答

bhdgx
bhdgx   2015.07.10 22:17

if((inet_pton(AF_INET, argv[1], &server_addr.sin_addr))<=0); 把最后那个 "; "去掉,之后connect的调用也有这个问题

save4me
save4me   Ds   Rxr 2015.07.10 22:41

server_addr.sin_port是unsigned short,改成server_addr.sin_port=htons(port);

devmiao
devmiao   Ds   Rxr 2015.07.10 23:18
lightlater
lightlater   2015.07.11 08:39

先检查有没有不符合语法规范的地方,再说调用的问题!

qq_28396927
qq_28396927   2015.07.11 09:30

是有几个语法错误,但是函数出错并不是这些原因,我把该了之后的code运行,还是一样的出错了,同样是inet_pton函数执行失败

 #include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<stdio.h>
#include<stdlib.h>
#include<strings.h>
void outputError(char *message)
{
    fprintf(stdout, "error:%s\n",message);
    exit(0);
}

int main(int argc, char *argv[])
{

    int sockFd;
    char receiveBuffer;
    struct sockaddr_in server_addr;
    int port=13;
    if(argc!=2)
    {
    outputError("usage:getTime <IPaddress>");
    }
    if((sockFd=socket(AF_INET, SOCK_STREAM, 0))<0)
    {
    outputError("socket occured error!");
    }
    bzero(&server_addr, sizeof(server_addr));
    server_addr.sin_family=AF_INET;
    server_addr.sin_port=htons(port);
    if((inet_pton(AF_INET, argv[1], &server_addr.sin_addr))<=0)
    {
    outputError("inet_pton occured error!");
    }
    if(connect(sockFd, (struct sockaddr*)&server_addr, sizeof(server_addr)<0))
    {
        outputError("connect to server failied");
    }
    while((read(sockFd, receiveBuffer, 1))==1)
    {
    fprintf(stdout, "%c", receiveBuffer);
    }
    exit(0);
}
CSDNXIAON
CSDNXIAON   2015.07.16 15:22

Unix网络编程卷一: 网络地址转换函数 (inet_pton和inet_ntop)
网络编程之inet_pton,inet_ntop,sock_ntop函数
----------------------同志你好,我是CSDN问答机器人小N,奉组织之命为你提供参考答案,编程尚未成功,同志仍需努力!

Csdn user default icon
上传中...
上传图片
插入图片