- 论坛徽章:
- 0
|
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <sys/socket.h>
- #include <sys/select.h>
- #include <fcntl.h>
- #include <sys/time.h>
- #include <sys/select.h>
- #include <arpa/inet.h>
- #include <netinet/in.h>
- #include <netinet/tcp.h>
- int testConnect(char *hostIp,int hostPort);
- void main()
- {
- char *hostIp="192.168.106.81";
- int hostPort= 514;
- int sts;
- sts = testConnect(hostIp,hostPort);
- if (sts == 0)
- {
- printf("Can't connect %d:%s now!",hostIp,hostPort);
- }
- else
- printf("%d:%s can be connected now!",hostIp,hostPort);
- }
- int testConnect(char *hostIp,int hostPort)
- {
- int s,flags,retcode;
- int err,len;
- struct sockaddr_in peer;
-
- char *srvip;
- int srvport;
- srvip=hostIp;
- srvport=hostPort;
-
- s = socket(AF_INET, SOCK_STREAM, 0);
- //下面获取套接字的标志
- if ((flags = fcntl(s, F_GETFL, 0)) < 0)
- {
- return 0;
- }
- //下面设置套接字为非阻塞
- if (fcntl(s, F_SETFL, flags | O_NONBLOCK) < 0)
- {
- return 0;
- }
-
- peer.sin_family = AF_INET;
- peer.sin_port = htons(srvport);
- peer.sin_addr.s_addr=inet_addr(srvip);
-
- retcode = connect(s, (struct sockaddr*)&peer, sizeof(peer));
- //如果connect()返回0则连接已建立,直接返回1
- if (retcode == 0) return 1;
- fd_set rdevents,wrevents,exevents;
-
- FD_ZERO(&rdevents);
- FD_SET(s, &rdevents); //把先前的套接字加到读集合里面
- wrevents = rdevents; //写集合
- exevents = rdevents; //异常集合
-
- struct timeval tv;
-
- tv.tv_sec = 1; //设置时间为1秒
- tv.tv_usec = 0;
-
- retcode = select(s+1, &rdevents, &wrevents, &exevents, &tv);
- if (retcode < 0)
- {
- return 0;
- }
- else if (retcode == 0)
- { //select 超时???
- return 0;
- }
- }
复制代码
编译时:cc testconnect.c
报错:
未定义 文件中的
符号 在文件中
socket testconnect.o
connect testconnect.o
inet_addr testconnect.o
ld: 致命的: 符号参照错误. 没有输出被写入a.out
请各位法师版主指点一二!THX~~ |
|