inet_pton()函式,編譯執行提示段錯誤
阿新 • • 發佈:2019-01-06
#include <string.h> #include "../include/apue.h" #include <sys/socket.h> #include <netinet/in.h> #include <sys/errno.h> int main(int argc, char **argv) { int sockfd, n; char recvline[MAXLINE + 1]; struct sockaddr_in servaddr; if(argc != 2) err_quit("Usage: ./a.out <IPAddress>"); if((sockfd = socket(PF_INET, SOCK_STREAM, 0)) < 0) err_quit("socket error!"); bzero(&servaddr, sizeof(servaddr)); //there is warning : bzero 不相容 memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(8008); //servaddr.sin_addr.s_addr = inet_addr(argv[1]); //inet_addr() only support IPv4 inet_pton(AF_INET, argv[1], &servaddr.sin_addr); //inet_pton() also can support IPv6 if( (connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr))) < 0) err_sys("connect error!"); while((n = read(sockfd, recvline, MAXLINE)) > 0) { recvline[n] = 0; //null terminate if(fputs(recvline, stdout) == EOF) err_sys("EOF"); } exit(0); }
同一.c檔案,在臺式機執行一切正常. 32位 XP
當複製到筆記本上編譯執行時竟然提示段錯誤.當時就好無奈. 果斷gcc -g 除錯,發現問題出在inet_pton().
好吧,找到了解決方法:
#include <apra/inet.h>即可.
原來筆記本是64位 WIN7,所以才會出現這種情況.