#include "stdafx.h"
#pragma comment(lib,"Ws2_32.lib")
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
WSADATA wsaData;
int Port = 27015;
int BufLen = 1024;
sockaddr_in SenderAddr;
int SenderAddrSize = sizeof(SenderAddr);
//-----------------------------------------------
// Initialize Winsock
WSAStartup(MAKEWORD(2,2), &wsaData);
SOCKET socket1;
struct sockaddr_in server;
int len =sizeof(server);
server.sin_family=AF_INET;
server.sin_port=htons(1000); ///server的监听端口
server.sin_addr.s_addr=inet_addr("192.168.250.17"); ///server的地址
socket1=socket(AF_INET,SOCK_DGRAM,0);
int time=1000;
setsockopt(socket1,SOL_SOCKET,SO_RCVTIMEO,(char*)&time, sizeof(time));
char buffer[1024]="/0";
printf("input message/n");
scanf("%s",buffer);
sendto(socket1,buffer,sizeof buffer,0,(struct sockaddr*)&server,len);
sockaddr_in rvaddr;
int nrvaddr=sizeof(rvaddr);
recvfrom(socket1,buffer,sizeof buffer,0,(struct sockaddr*)&rvaddr,&nrvaddr);
closesocket(socket1);
return 0;
}
如果你连接的是本机地址,那setsockopt设置了SO_RCVTIMEO会立刻超时。但是如果inet_addr填入的是别的机器的地址这个函数就正常了。
为什么没有人提出注明呢?我就觉得我的程序一下正常一下不正常。。。。。