这是我第一次尝试编写网络程序。它编译没有问题,但是当我运行它时,它给了我一个“分段错误 11”。我希望有人能给我线索代码中的什么可能导致这个问题。
我是 C 的新人。
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <netdb.h>
#include <netinet/in.h>
int main()
{
//////////// GETADDRINFO \\\\\\\\\\\\\\\\
struct addrinfo hints, *res;
memset(&hints, 0 , sizeof hints);
hints.ai_family = AF_UNSPEC; //define the 'hints' strucure
hints.ai_socktype = SOCK_STREAM; //define the 'hints' strucure
hints.ai_protocol = AI_PASSIVE; //define the 'hints' strucure
char *ipaddr = "127.0.0.1";
getaddrinfo(ipaddr, "ftp", &hints, &res);
////////////// SOCKET \\\\\\\\\\\\\\\\
int sock = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in info;
int bnd = bind( sock , res->ai_addr, res->ai_addrlen);
info.sin_family = AF_INET;
info.sin_port = htons(10000);
info.sin_addr.s_addr = INADDR_ANY;
bzero(&(info.sin_zero),8);
/////////////// CONNECT \\\\\\\\\\\\\\\\\\\\\\
int conct = connect( sock, res->ai_addr, res->ai_addrlen);
////////////// LISTEN \\\\\\\\\\\\\\\\\\
int lstn = listen( sock , 4 );
////////////// ACCEPT \\\\\\\\\\\\\\\\\\\\\\\
int new_fd;
struct sockaddr_storage client_addr;
socklen_t addr_size;
addr_size = sizeof(client_addr);
new_fd = accept(sock, (struct sockaddr *)&client_addr, &addr_size);
///////////////// SEND \\\\\\\\\\\\\\\\\\\\\\
char *msg = "HI!";
int len, bytes_sent;
len = strlen(msg);
bytes_sent = send(sock, msg, len, 0);
//////////////// RECEIVE \\\\\\\\\\\\\\\\\
char burr[254];
int cat = sizeof(burr);
recv( sock, burr , cat , 0 );
printf("%s", burr);
return 0;
}