【发布时间】:2014-11-06 20:23:06
【问题描述】:
我正在编写一个 C 程序以通过套接字在两个进程之间进行通信,并且我在调用连接函数时收到以下错误。
connect:: 参数无效
我在连接呼叫中遗漏了什么? 任何帮助都会很棒!
这是我的代码 -
void conn(char *hname)
{
struct hostent *hp;
struct sockaddr_in sin;
int port = 10000;
int s, rc;
hp = gethostbyname(hname);
if ( hp == NULL ) {
fprintf(stderr, "host not found (%s)\n", hname);
exit(1);
}
s = socket(AF_INET, SOCK_STREAM, 0);
if ( s < 0 ) {
perror("socket:");
exit(left);
}
sin.sin_family = AF_INET;
sin.sin_port = htons(port);
memcpy(&sin.sin_addr, hp->h_addr_list[0], hp->h_length);
rc = connect(s, (struct sockaddr *)&sin, sizeof(sin));
if ( rc < 0 ) {
perror("connect:");
exit(rc);
}
}
【问题讨论】:
-
这就是您遇到的所有错误吗?尝试使用 clang 编译以获取更多详细信息。
-
我拿走了你的代码,添加了
char hname[] = "google.com"并将端口更改为80,并成功连接到google...这是在Ubuntu Linux 14.04上完成的。 -
struct sockaddr_in有五个字段。你只填了三个。我一般memset整个烂到0才用。