当前位置: 技术问答>linux和unix
一个connect连接函数的疑惑
来源: 互联网 发布时间:2016-09-19
本文导语: #include "common.h" int do_connect(char *ip,struct sockaddr_in *sin,int *sock_fd); int main(void) { int sock_fd; struct sockaddr_in sin; char ip[20]="192.168.1.14"; do_connect(ip,&sin,&sock_fd); char str[250]="connect successful!n"; write(sock_fd,str,strlen(str)+1); re...
#include "common.h"
int do_connect(char *ip,struct sockaddr_in *sin,int *sock_fd);
int main(void)
{
int sock_fd;
struct sockaddr_in sin;
char ip[20]="192.168.1.14";
do_connect(ip,&sin,&sock_fd);
char str[250]="connect successful!n";
write(sock_fd,str,strlen(str)+1);
return 0;
}
int do_connect(char *ip,struct sockaddr_in *sin,int *sock_fd)
{
int sfd;
bzero(sin,sizeof(struct sockaddr_in));
sin->sin_family=AF_INET;
if(inet_pton(AF_INET,ip,&sin->sin_addr)==-1)
{
perror("wrong format of ip address");
return -1;
}
sin->sin_port=htons(8000);
if(sfd=socket(AF_INET,SOCK_STREAM,0)==-1)
{
perror("fail to creat socket");
return -1;
}
if(connect(sfd,(struct sockaddr *)sin,sizeof(struct sockaddr_in))==-1)
{
perror("fail to connect");
return -1;
}
*sock_fd=sfd;
return 0;
}
我用这个连我的服务器端,连不到。
结果是:"fail to connect: Socket operation on non-socket
connect successful!"
请各位高人指点一下迷津,谢谢。
|