我正在尝试通过执行非阻塞连接来检查网络上的主机,然后执行选择以查看套接字是否可写或异常不足。我尝试通过端口 80,139 建立套接字连接。主机如果套接字在连接之后是可写的,或者当主机发送 RST 数据包等时它进入异常时,将可以发现。
我已经使用 Windows 套接字编写了一个代码并且逻辑工作正常,但是使用 linux 套接字程序没有给出期望的结果。即使该 ip 上没有主机,选择函数也会为任何给定的 ip 地址返回 1。选择会winsock 的情况下返回 0 超时。我写了下面的代码,让我知道问题到底出在哪里。
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <stdio.h>
#include <sys/fcntl.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
int port[]={80,139};
void Free(int Sock_Arr[])
{
for(int i=0;i<2;i++)
{
close(Sock_Arr[i]);
}
return ;
}
int main()
{
int Socket[2],result=0; //Socket array
struct sockaddr_in service;
fd_set writefds;
fd_set exceptfds;
struct timeval timer;
timer.tv_sec=5;
timer.tv_usec=0;
int flag=0;
FD_ZERO(&writefds);
FD_ZERO(&exceptfds);
char Ip_Addr[20];
for(int i=0;i<2;i++)
{
if((Socket[i]=socket(AF_INET, SOCK_STREAM, IPPROTO_IP)) < 0)
{
Free(Socket);
}
fcntl(Socket[i],F_SETFL,O_NONBLOCK);
}
bzero(&service, sizeof(sockaddr_in));
printf("Enter the ip-address : ");
scanf("%s",Ip_Addr);
service.sin_family=AF_INET;
service.sin_addr.s_addr=inet_addr(Ip_Addr);
for(int i=0;i<2;i++)
{
FD_SET(Socket[i],&writefds);
FD_SET(Socket[i],&exceptfds);
service.sin_port=htons((unsigned short int )port[i]);
connect(Socket[i],(struct sockaddr *)&service,sizeof(sockaddr_in));
result= select(Socket[i]+1,NULL,&writefds,&exceptfds,&timer);
if(result<0||result==0)
{
flag=0;
printf("\n The machine could not be found on the port %d ",port[i]);
printf("result : %d",result);
perror("select");
}
else
{
printf("\n The machine could be found on the port %d ",port[i]);
flag=1;
printf("result : %d",result);
if(FD_ISSET(Socket[i],&writefds))
{
printf("The socket triggered on write on port %d",port[i]);
}
else if(FD_ISSET(Socket[i],&exceptfds))
{
printf("The socket triggered on except on port %d",port[i]);
}
else
{
printf("No socket triggered on %d",port[i]);
}
}
FD_ZERO(&writefds);
FD_ZERO(&exceptfds);
}
Free(Socket);
if(flag==1)
{
return 1;
}
else
{
return 0;
}
}