我通常不会为sigsegv错误转到stackoverflow,但我现在已经尽力使用我的调试器了.
完成该功能后,将抛出分段错误错误.我忽略了什么想法?我怀疑这是因为将sockaddr投射到sockaddr_in,但我无法在那里发现任何错误.(删除该行可以摆脱seg错误 - 但我知道这可能不是这里的根本原因).
// basic setup int sockfd; char str[INET_ADDRSTRLEN]; sockaddr* sa; socklen_t* sl; struct addrinfo hints, *servinfo, *p; int rv; memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; // return string string foundIP; // setup the struct for a connection with selected IP if ((rv = getaddrinfo("4.2.2.1", NULL, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); return "1"; } // loop through all the results and make a socket for(p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("talker: socket"); continue; } break; } if (p == NULL) { fprintf(stderr, "talker: failed to bind socket\n"); return "2"; } // connect the UDP socket to something connect(sockfd, p->ai_addr, p->ai_addrlen); // we need to connect to get the systems local IP // get information on the local IP from the socket we created getsockname(sockfd, sa, sl); // convert the sockaddr to a sockaddr_in via casting struct sockaddr_in *sa_ipv4 = (struct sockaddr_in *)sa; // get the IP from the sockaddr_in and print it inet_ntop(AF_INET, &(sa_ipv4->sin_addr), str, INET_ADDRSTRLEN); printf("%s\n", str); // return the IP return foundIP;
}
它看起来不像你初始化指针sa
指向有效sockaddr
(或sockaddr_in
)对象.
如果你更换
sockaddr* sa;
同
sockaddr addr;
和替换的所有使用sa
与&addr
你应该在更好的状态.
同样的情况也是如此sl
.至少根据用于我的getsockname文档中的socklen_t*
参数需要在有效点socklen_t
的地址缓冲区的字节数初始化为大小的对象.
例如
socklen_t slen = sizeof addr;
并使用&slen
而不是sl
.