VC中,如何获取客户端IP

// VPSTest.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <process.h>
#include "WinSock2.h"
#include <cstdlib>
#include <assert.h>
#pragma comment(lib,"ws2_32.lib")
using namespace std;

DWORD WINAPI AnswerThread(LPVOID lparam)
{

SOCKET cliSocket = (SOCKET)(LPVOID)lparam;
SOCKADDR_IN cliaddr;
char clibuf[100];
int len=sizeof(SOCKADDR);
memset((void *)&cliaddr,0,sizeof(cliaddr));
getpeername( cliSocket, (struct sockaddr FAR *)&cliaddr, &len ) ; //这句很重要,只有写了这个,才能正确的获取cliaddr的内容的,否则,不是0.0.0.0,就是204.204.204.204;

while (true)
{
int nRevLength = 0;
if (-1 != (nRevLength = recvfrom(cliSocket,clibuf,100,0,(SOCKADDR*)&cliaddr,&len)))
{
printf("Good: Receive Length = %d \n", nRevLength);
printf("对方IP:%s\n",inet_ntoa(cliaddr.sin_addr));//问题从这可以看出来。
printf("%s\n\n",clibuf);
int rrr = WSAGetLastError();
printf("%d\n\n",rrr);
}
else
{
printf("Error: Receive Length = %d \nReceive thread will quit.\n", nRevLength);
break;
}

Sleep(100);
}

closesocket(cliSocket);
return 0;
}

 

void _tmain(int arcg,_TCHAR* argv[])
{
WORD wVersionRequested;
WSADATA wsaData;
int err;

//构建保存版本号的WORD类型变量
wVersionRequested = MAKEWORD( 2, 2 );

//加载套接字库
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 )
{
return;
}

//检查加载的套接字库版本和请求的是否一致
if ( LOBYTE( wsaData.wVersion ) != 2 ||
HIBYTE( wsaData.wVersion ) != 2 )
{
WSACleanup( );
return;
}

//创建套接字,第一个参数是地址族 TCP/IP下始终为AF_INET,第二个参数表示流式套接字,第三个参数指定协议,0表示系统自选协议 而对于流式套接字 系统的自选协议就是TCP协议
SOCKET socksev=socket(AF_INET,SOCK_STREAM,NULL);

//定义地址结构体 并初始
SOCKADDR_IN sevaddr;
sevaddr.sin_addr.S_un.S_addr=htonl(INADDR_ANY);
sevaddr.sin_family=AF_INET;
sevaddr.sin_port=htons(1234);

bind(socksev,(SOCKADDR*)&sevaddr,sizeof(SOCKADDR));
int nListen = listen(socksev, SOMAXCONN);
if(nListen == SOCKET_ERROR)
{
assert(false);
}

while(1)
{
SOCKET newsocket;
struct sockaddr_in clientaddr;
int length;
length = sizeof(struct sockaddr_in);
newsocket = accept(socksev, NULL,NULL);

if(newsocket == INVALID_SOCKET)
{
printf("accept fail !");
}
else
{
printf("accept true, start a receive thread.\n");
CreateThread(NULL,NULL, AnswerThread,(LPVOID)newsocket, 0, 0);
}
}
closesocket(socksev);
WSACleanup();
}

你可能感兴趣的:(客户端)