---
title: "VC++实现NAT穿透之NAT类型检测"
author: "winzenghua"
date: "2009-08-26T13:30:00Z"
tags: []
slug: "vc-nat-nat"
draft: false
lastmod: "2009-08-26T13:30:00Z"
id: 948112
url: "https://java4gis.iteye.com/blog/948112"
---

// NatCheck.cpp : Defines the entry point for the console application.  
//

#include "stdafx.h"  
#include &lt;process.h&gt;  
#include &lt;stdio.h&gt;  
#include &lt;afx.h&gt;  
#include "winsock2.h"  
#include "./Include/packet.h"  
#pragmacomment(lib,"./lib/wininet.lib")  
#pragmacomment(lib,"wsock32.lib")  
#include "ws2tcpip.h"  
#include "string.h"

#define N\_SuperNode 5  
#define N\_NatCheckRequestQueue 20  
#define PORT\_SERVER\_NATCHECK 8888  
#define PORT\_SERVER\_NATCHECK\_1 8889  
#define PORT\_CLIENT\_NATCHECK 7777  
#define PORT\_SERVER\_CLIENT\_INFO 4444  
#define N\_CheckTime 5 //最多检测次数

SOCKET sClient,sServer;//客户端和服务端的socket号  
struct sockaddr\_in sn1\_addr,sn2\_addr,sn\_addr,client\_addr;  
struct sockaddr\_in client\_addr\_deal;  
struct in\_addr in\_addr\_tmp,in\_addr\_tmp1;  
FILE \*fp; //客户端读取hostcache.txt文件指针  
int i=0,j=0;  
unsigned long int snIP\[N\_SuperNode];//读取的SN的IP地址列表  
unsigned short int snPort\[N\_SuperNode];//读取的SN的Port列表  
char tmpIP\[15],tmpPort\[5];  
char ch;  
char IP\_return\[15];  
/* 本client的网络类型：  
\*0 = public net  
\*1 = full cone nat  
\*2 = symmetric nat  
\*3 = restricted cone nat  
\*4 = port restricted cone nat  
\*/  
unsigned long int myID=0,friendID=26;//本client和friend的用户ID  
char myNetType=-1,friendNetType=-1;  
unsigned long int myPubIp,friendPubIp,myPriIp,friendPriIp;  
unsigned short int myPubPort,friendPubPort,myPriPort,friendPriPort;  
//natCheck请求包结构  
struct natCheckPacket{  
char version;  
char dowhat;  
unsigned short int port;  
unsigned long int ip;  
unsigned long int id;  
}natCheckPacket;  
typedef struct natCheckPacket NCP;  
char buff\[sizeof(natCheckPacket)];//发包用的缓冲区  
//natCheck请求数据结构  
struct natCheckRequest{  
NCP ncp;//缓存到来的请求包  
struct natCheckRequest * next;//指向下一个请求数据  
unsigned long int ip;//发送请求的client IP地址  
unsigned short int port;//发送请求的client Port  
}natCheckRequest;  
typedef struct natCheckRequest NCR;  
struct netInfoResponsePacket{  
NCP ncp;  
unsigned long int ip\_pub;  
unsigned short int port\_pub;  
unsigned short int no;  
}netInfoResponsePacket;  
typedef struct netInfoResponsePacket NIRP;  
//natCheck请求数据循环队列  
NCR natCheckRequestQueue\[N\_NatCheckRequestQueue];  
NCR * h\_NatCheckRequestQueue,* t\_NatCheckRequestQueue;  
/*  
\*获得本地主机IP地址  
\*/  
char * getownIP()  
{  
//////////////////  
// 获得主机名.  
char hostname\[256];  
int res = gethostname(hostname, sizeof(hostname));  
if (res != 0) {  
printf("Error: %u\\n", WSAGetLastError());  
return "failed";  
}  
////////////////  
// 根据主机名获取主机信息.  
hostent* pHostent = gethostbyname(hostname);  
if (pHostent==NULL) {  
printf("Error: %u\\n", WSAGetLastError());  
return "failed";  
}  
//////////////////  
// 解析返回的hostent信息.  
hostent& he = \*pHostent;  
sockaddr\_in sa;  
memcpy ( &sa.sin\_addr.s\_addr, he.h\_addr\_list\[0],he.h\_length);  
return inet\_ntoa(sa.sin\_addr);  
}  
unsigned long int getownIP\_uli()  
{  
//////////////////  
// 获得主机名.  
char hostname\[256];  
int res = gethostname(hostname, sizeof(hostname));  
if (res != 0) {  
printf("Error: %u\\n", WSAGetLastError());  
return -1;  
}  
////////////////  
// 根据主机名获取主机信息.  
hostent* pHostent = gethostbyname(hostname);  
if (pHostent==NULL) {  
printf("Error: %u\\n", WSAGetLastError());  
return -1;  
}  
//////////////////  
// 解析返回的hostent信息.  
hostent& he = \*pHostent;  
sockaddr\_in sa;  
memcpy ( &sa.sin\_addr.s\_addr, he.h\_addr\_list\[0],he.h\_length);  
return sa.sin\_addr.S\_un.S\_addr;  
}  
/*  
\*superNode接收请求线程入口函数  
\*/  
unsigned int \_stdcall ThreadFunction\_sn\_get(void \*param)  
{  
//创建套接字  
if( (sServer = socket(AF\_INET, SOCK\_DGRAM, IPPROTO\_UDP)) &lt; 0)  
{  
printf("获取SOCKET号失败!!!\\n");  
return 0;  
}  
//绑定套接字和本机地址和端口  
sn\_addr.sin\_family=AF\_INET;  
sn\_addr.sin\_port=htons(PORT\_SERVER\_NATCHECK);  
sn\_addr.sin\_addr.s\_addr =INADDR\_ANY ;//inet\_addr(getownIP()); //  
if(bind(sServer, (struct sockaddr\*)&sn\_addr, sizeof(sn\_addr)) &lt; 0 )  
{  
printf("不能将服务器地址捆绑到SOCKET号上!!!\\n");  
closesocket(sServer);  
return 0;  
}  
//printf("接收....\\n");  
int iLen=sizeof(client\_addr);  
struct natCheckPacket * ncp=(struct natCheckPacket \*)buff;  
int timeout=300;  
while (1)  
{  
setsockopt(sServer, SOL\_SOCKET, SO\_RCVTIMEO, (char \*)&timeout,sizeof(timeout));  
if(recvfrom(sServer,buff,sizeof(buff),0,(sockaddr\*)&client\_addr,&iLen)!=-1)  
{  
//判断队列是否满  
if(t\_NatCheckRequestQueue-&gt;next!=h\_NatCheckRequestQueue)  
{  
//先修改t  
NCR * t=t\_NatCheckRequestQueue;  
t\_NatCheckRequestQueue=t-&gt;next;  
//再写入  
t-&gt;ncp=\*(ncp);  
t-&gt;ip=client\_addr.sin\_addr.S\_un.S\_addr;  
t-&gt;port=client\_addr.sin\_port;  
}  
}  
Sleep(300);  
//printf("version:%d\\tdowhat:%d\\tport:%d\\tip:%d\\n",ncp-&gt;version,ncp-&gt;dowhat,  
//ncp-&gt;port,ncp-&gt;ip);  
//printf("Client said: %s\\n",buff);  
//strcpy(buff,"I am a server!!\\n");  
//sendto(sServer,buff,sizeof(buff),0,(sockaddr\*)&client\_addr,sizeof(client\_addr));  
}  
//closesocket(sServer);  
return 0;  
}  
/*  
\*构造NCP包发送给SuperNode  
\*接受返回的NCP包  
\*/  
int sendNCPtoSNandRecvNCP(unsigned long int ip\_SN,unsigned short int port\_SN,  
NCP ncp\_send)  
{  
int timeout=300;  
sn\_addr.sin\_addr.S\_un.S\_addr=ip\_SN;  
sn\_addr.sin\_family=AF\_INET;  
sn\_addr.sin\_port=htons(port\_SN);  
int iLen=sizeof(sn\_addr);  
NCP * ncp=(NCP \*)buff;  
ncp-&gt;version=ncp\_send.version;  
ncp-&gt;dowhat=ncp\_send.dowhat;  
ncp-&gt;port=ncp\_send.port;  
ncp-&gt;ip=ncp\_send.ip;  
ncp-&gt;id=ncp\_send.id;  
setsockopt(sClient, SOL\_SOCKET , SO\_SNDTIMEO, (char \*)&timeout,sizeof(timeout));  
sendto(sClient,buff,sizeof(buff),0,(SOCKADDR\*)&sn\_addr,iLen);  
in\_addr\_tmp.S\_un.S\_addr=ip\_SN;  
in\_addr\_tmp1.S\_un.S\_addr=ncp-&gt;ip;  
char * ipaddr=NULL;  
char addr\[15];  
in\_addr inaddr;  
inaddr. s\_addr=ncp-&gt;ip;  
ipaddr= inet\_ntoa(inaddr);  
strcpy(addr,ipaddr);  
printf("\[send]\[SN(%s)]\\n\\tversion:%d\\tdowhat:%d\\tport:%d\\tip:%s\\n",inet\_ntoa(in\_addr\_tmp),  
ncp-&gt;version,ncp-&gt;dowhat,ncp-&gt;port,addr);  
timeout=1500;  
setsockopt(sClient, SOL\_SOCKET, SO\_RCVTIMEO, (char \*)&timeout,sizeof(timeout));  
if(recvfrom(sClient,buff,sizeof(buff),0,(sockaddr\*)&sn\_addr,&iLen)&lt;0)  
return 0;  
else  
{  
inaddr. s\_addr=sn\_addr.sin\_addr.S\_un.S\_addr;  
ipaddr= inet\_ntoa(inaddr);  
strcpy(addr,ipaddr);  
in\_addr\_tmp.S\_un.S\_addr=((NCP \*)buff)-&gt;ip;  
printf("\[rece]\[sn(%s)]\\n\\tversion:%d\\tdowhat:%d\\tport:%d\\tip:%s\\n",addr,((NCP \*)buff)-&gt;version,  
((NCP \*)buff)-&gt;dowhat,ntohs(((NCP \*)buff)-&gt;port),inet\_ntoa(in\_addr\_tmp));  
return 1;  
}  
}  
/*  
\*构造NCP包发送给SuperNode  
\*接受返回的NIRP包  
\*/  
int sendNCPtoSNandRecvNIRP(unsigned long int ip\_SN,unsigned short int port\_SN,  
NCP ncp\_send)  
{  
FILE * fp\_n;  
FILE * fp\_c;//for compare  
//打开文件natCheckResult.txt  
if(!(fp\_n=fopen("./natCheckResult.txt","a")))  
{  
printf("natCheckResult.txt file not found!\\n");  
return 0;  
}  
char one\_line\[100],one\_line\_f\[100];  
int timeout=300;  
sn\_addr.sin\_addr.S\_un.S\_addr=ip\_SN;  
sn\_addr.sin\_family=AF\_INET;  
sn\_addr.sin\_port=htons(port\_SN);  
int iLen=sizeof(sn\_addr);  
char buff\_recv\[sizeof(NIRP)];  
NCP * ncp=(NCP \*)buff;  
NIRP * nirp=(NIRP \*)buff\_recv;  
ncp-&gt;version=ncp\_send.version;  
ncp-&gt;dowhat=ncp\_send.dowhat;  
ncp-&gt;port=ncp\_send.port;  
ncp-&gt;ip=ncp\_send.ip;  
ncp-&gt;id=ncp\_send.id;  
setsockopt(sClient, SOL\_SOCKET , SO\_SNDTIMEO, (char \*)&timeout,sizeof(timeout));  
sendto(sClient,buff,sizeof(buff),0,(SOCKADDR\*)&sn\_addr,iLen);  
in\_addr\_tmp.S\_un.S\_addr=ip\_SN;  
in\_addr\_tmp1.S\_un.S\_addr=ncp-&gt;ip;  
char * ipaddr=NULL;  
char addr\[15];  
in\_addr inaddr;  
inaddr. s\_addr=ncp-&gt;ip;  
ipaddr= inet\_ntoa(inaddr);  
strcpy(addr,ipaddr);  
printf("\[send]\[SN(%s)]\\n\\tversion:%d\\tdowhat:%d\\tport:%d\\tip:%s\\n",  
inet\_ntoa(in\_addr\_tmp),ncp-&gt;version,ncp-&gt;dowhat,ncp-&gt;port,addr);  
timeout=1500;  
setsockopt(sClient, SOL\_SOCKET, SO\_RCVTIMEO, (char \*)&timeout,sizeof(timeout));  
int stop=0;  
while(!stop)  
{  
setsockopt(sClient, SOL\_SOCKET, SO\_RCVTIMEO, (char \*)&timeout,sizeof(timeout));  
if(recvfrom(sClient,buff\_recv,sizeof(buff\_recv),0,(sockaddr\*)&sn\_addr,&iLen)&lt;0)  
stop=1;  
else  
{  
sprintf(one\_line,"%u %u %u %u %u %u",  
((NIRP \*)buff\_recv)-&gt;ncp.id,  
((NIRP \*)buff\_recv)-&gt;ncp.dowhat,  
((NIRP \*)buff\_recv)-&gt;ip\_pub,  
((NIRP \*)buff\_recv)-&gt;port\_pub,  
((NIRP \*)buff\_recv)-&gt;ncp.ip,  
((NIRP \*)buff\_recv)-&gt;ncp.port);  
printf("%s\\n",one\_line);  
friendNetType=((NIRP \*)buff\_recv)-&gt;ncp.dowhat;  
friendPubIp=((NIRP \*)buff\_recv)-&gt;ip\_pub;  
friendPubPort=((NIRP \*)buff\_recv)-&gt;port\_pub;  
friendPriIp=((NIRP \*)buff\_recv)-&gt;ncp.ip;  
friendPriPort=((NIRP \*)buff\_recv)-&gt;ncp.port;  
//打开文件natCheckResult.txt  
if(!(fp\_c=fopen("./natCheckResult.txt","r")))  
{  
printf("natCheckResult.txt file not found!\\n");  
return 0;  
}  
while(!feof(fp\_c))  
{  
i=0;  
while((ch=fgetc(fp\_c))!=10 && ch!=-1)  
one\_line\_f\[i++]=ch;  
if(ch==-1)  
break;  
one\_line\_f\[i]='\\0';  
if(strcmp(one\_line,one\_line\_f)==0)  
{  
fclose(fp\_c);  
fclose(fp\_n);  
return 1;  
}  
}

fprintf(fp\_n,"%s\\n",one\_line);  
fflush(fp\_n);  
}  
}  
fclose(fp\_c);  
fclose(fp\_n);  
return 1;  
}  
void longIP2string(unsigned long int ip,char* addr)  
{  
in\_addr inaddr;  
char * ipaddr=NULL;  
inaddr. s\_addr=sn\_addr.sin\_addr.S\_un.S\_addr;  
ipaddr= inet\_ntoa(inaddr);  
strcpy(addr,ipaddr);  
}  
/*  
\*从client端的hostcache.txt文件获取一个SN  
\* 写入ip\_SN,port\_SN  
\* 如果文件已经到结尾，或者文件语法错误，则返回0  
\*/  
int getSNfromHostCache(FILE * fp,unsigned long int &ip\_SN,unsigned short int &port\_SN)  
{  
if(feof(fp))  
return 0;  
i=0;  
while((ch=fgetc(fp))!=' ' && ch!=10 && ch!=-1)  
tmpIP\[i++]=ch;  
if(ch==10 || ch==-1)  
{  
printf("hostcache.txt file error!\\n");  
return 0;  
}  
tmpIP\[i]='\\0';  
i=0;  
while((ch=fgetc(fp))!=10 && ch!=-1)  
tmpPort\[i++]=ch;  
tmpPort\[i]='\\0';  
ip\_SN=inet\_addr(tmpIP);  
port\_SN=(unsigned short int)atoi(tmpPort);  
return 1;  
}  
/*  
\*client最先知道检测结果  
\* client需要向自己缓存的SN节点汇报自己的网络类型信息  
\* 这里依然使用了NCP包  
void broadcastNatCheckResult(char version,  
char dowhat,unsigned long int ip,unsigned short int port,  
unsigned long int id)  
\*/  
void broadcastNatCheckResult(NCP ncp\_send)  
{  
FILE * fp\_b=fp;  
fseek(fp\_b,0L,0);  
while (!feof(fp\_b)) {  
i=0;  
while((ch=fgetc(fp\_b))!=' ' && ch!=10 && ch!=-1)  
tmpIP\[i++]=ch;  
if(ch==10 || ch==-1)  
{  
printf("hostcache.txt file error!\\n");  
return;  
}  
tmpIP\[i]='\\0';  
i=0;  
while((ch=fgetc(fp\_b))!=10 && ch!=-1)  
tmpPort\[i++]=ch;  
tmpPort\[i]='\\0';  
int timeout=300;  
sn\_addr.sin\_addr.S\_un.S\_addr=inet\_addr(tmpIP);  
sn\_addr.sin\_family=AF\_INET;  
sn\_addr.sin\_port=htons((unsigned short int)atoi(tmpPort));  
int iLen=sizeof(sn\_addr);  
NCP * ncp=(NCP \*)buff;  
ncp-&gt;version=ncp\_send.version;  
ncp-&gt;dowhat=ncp\_send.dowhat;  
ncp-&gt;port=ncp\_send.port;  
ncp-&gt;ip=ncp\_send.ip;  
ncp-&gt;id=ncp\_send.id;  
setsockopt(sClient, SOL\_SOCKET , SO\_SNDTIMEO, (char \*)&timeout,sizeof(timeout));  
sendto(sClient,buff,sizeof(buff),0,(SOCKADDR\*)&sn\_addr,iLen);  
}  
fclose(fp\_b);  
return;  
}  
/*  
\*SN收到client汇报的结果，  
\*向NatCheckResult.txt 写入id 网络类型 外网ip port 内网ip port  
\*/  
int storeNatCheckResult(unsigned long int id,char type,  
unsigned long int pub\_ip,unsigned short int pub\_port,  
unsigned long int pri\_ip,unsigned short int pri\_port)  
{  
FILE * fp\_n;  
char one\_line\[100],one\_line\_f\[100];  
sprintf(one\_line,"%u %u %u %u %u %u",id,type,pub\_ip,pub\_port,pri\_ip,pri\_port);  
//打开文件natCheckResult.txt  
if(!(fp\_n=fopen("./natCheckResult.txt","rw")))  
{  
printf("natCheckResult.txt file not found!\\n");  
return 0;  
}  
while(!feof(fp\_n))  
{  
i=0;  
while((ch=fgetc(fp\_n))!=10 && ch!=-1)  
one\_line\_f\[i++]=ch;  
if(ch==-1)  
{  
break;  
}  
one\_line\_f\[i]='\\0';  
if(strcmp(one\_line,one\_line\_f)==0)  
return 0;  
}  
fclose(fp\_n);  
if(!(fp\_n=fopen("./natCheckResult.txt","a")))  
{  
printf("natCheckResult.txt file not found!\\n");  
return 0;  
}  
fprintf(fp\_n,"%u %u %u %u %u %u\\n",id,type,pub\_ip,pub\_port,pri\_ip,pri\_port);  
printf("%u %u %u %u %u %u\\n",id,type,pub\_ip,pub\_port,pri\_ip,pri\_port);  
fflush(fp\_n);  
fclose(fp\_n);  
return 1;  
}  
/*  
\*SN收到client的查询请求，  
\*从NatCheckResult.txt 中查找id对应的 网络类型 外网ip port 内网ip port  
\*/  
int searchNatCheckResult(NCP ncp,SOCKET sServer,sockaddr\_in addr)  
{  
FILE * fp\_n;  
char id\[32];  
//打开文件natCheckResult.txt  
if(!(fp\_n=fopen("./natCheckResult.txt","r")))  
{  
printf("natCheckResult.txt file not found!\\n");  
return 0;  
}  
int j=0;  
while(!feof(fp\_n))  
{  
i=0;  
while((ch=fgetc(fp\_n))!=' ' && ch!=10 && ch!=-1)  
id\[i++]=ch;  
if(ch==10)  
{  
printf("natCheckResult.txt file error!\\n");  
return 0;  
}  
if(ch==-1)  
{  
break;  
}  
id\[i]='\\0';  
if(ncp.id!=(unsigned long int)atoi(id))  
{  
while(fgetc(fp\_n)!=10);  
continue;  
}  
unsigned long int ip\_pub;  
unsigned short int port\_pub;  
fscanf(fp\_n,"%d %d %d %d %d\\n",&(ncp.dowhat),&ip\_pub,&port\_pub,&(ncp.ip),&(ncp.port));  
char buff\_send\[sizeof(NIRP)];  
NIRP * nirp = (NIRP \*) buff\_send;  
nirp-&gt;ncp=ncp;  
nirp-&gt;ip\_pub=ip\_pub;  
nirp-&gt;port\_pub=port\_pub;  
nirp-&gt;no=j++;  
sendto(sServer,buff\_send,sizeof(buff\_send),0,(sockaddr\*)&addr,sizeof(addr));  
}  
fclose(fp\_n);  
return 1;  
}  
/*  
\*main函数  
\*/  
int main(int argc, char* argv\[])  
{  
if(argc &lt; 2)  
{  
printf("usage: %s -c or -s \\n", argv\[0]);  
printf("-c: for clients\\n-s: for superNode\\n");  
return 0;  
}  
//////////////////  
// 初始化winsock环境.  
WSADATA wsadata;  
WORD wVersion=MAKEWORD(2,0);//winsock 2.0  
if(WSAStartup(wVersion,&wsadata)!=0)  
{  
printf("winsocket initalize failed!\\n");  
WSACleanup();  
return 0;  
}  
///////////////////////////////////////////////////////////////////  
//客户端程序入口  
////////////////////////////////////////////////////////////////////  
if(strcmp(argv\[1],"-c")==0)  
{  
if(argc&gt;=3)  
myID=atoi(argv\[2]);  
NCP ncp\_send;  
ncp\_send.version=0;  
ncp\_send.id=myID;  
//////////////////  
// 读取hostcache文件中的前两个supernode  
if(!(fp=fopen("./hostcache.txt","r")))  
{  
printf("hostcache.txt file not found!\\n");  
return 0;  
}  
if( (sClient=socket(AF\_INET,SOCK\_DGRAM,IPPROTO\_UDP)) &lt; 0)  
{  
printf("获取SOCKET号失败!!!\\n");  
return 0;  
}  
myPriIp=inet\_addr(getownIP());  
myPriPort=htons(PORT\_CLIENT\_NATCHECK);  
client\_addr.sin\_addr.S\_un.S\_addr=INADDR\_ANY; /* use my IP address \*/  
client\_addr.sin\_family=AF\_INET;  
client\_addr.sin\_port=htons(PORT\_CLIENT\_NATCHECK);  
printf("\[info]client ip=%s\\tport:%d\\n",getownIP(),ntohs(myPriPort));  
//bind(int sockfd, const struct sockaddr \*my\_addr, int addrlen);  
if(bind(sClient,(struct sockaddr\*)&client\_addr,sizeof(client\_addr))&lt;0)  
{  
printf("不能捆绑到SOCKET号上!!!\\n");  
closesocket(sClient);  
return 0;  
}  
/\*/////////////////////////////////////////////////////////////////////////////////////  
//NAT检测开始  
//检测流程：  
1.向超级节点SN1发送0号包，等待一段超时时间，如果没有返回，换下一个超级节点。  
否则go 2，如果hostcache中的节点都失效了，那么开始向中心节点发请求，来得到一批  
新的superNode节点列表；  
2.判断超级节点返回的7号包中携带的(ip,port)和自己发包时用的(ip,port)是否相同，  
如果相同的话，说明本地是公网IP；如果不同的话，说明在NAT后；  
3.向SN1发送1号包，并携带一个自己列表中的另一个superNode，SN2的(ip,port)，让SN1  
发8号包给SN2，告诉本client的外网(ip,port)，让SN2给本client发6号包；另外SN1还可  
以在自己维护的临近的SN列表中选择3个也给client发送6号包。  
4.如果client在一段超时时间内，没有收到任何包，那么在将3中的过程进行一次，总共最多  
可以进行N\_CheckTime(5)次。其中只要有一次收到包，就go 5。  
5.如果收到了SN2、SN3、SN4中的任何一个，检测就停止，结果是full cone Nat。如果没有  
收到任何包，检测继续，go 6  
6.client从自己的hostcache中选择一个SN2，向其发送2号包，等待一段超时时间，如果没有  
收到5号包的话，继续从hostcache中另选择一个SN3，如果hostcache中的所有SN都不给回应  
5号包的话，从中心节点获取新的SN后，继续发2号包。收到第一个5号包，开始比较，如果和  
SN1的返回结果(ip,port)中如果有任何一对不一致，则说明是Symmetric NAT，检测停止。  
否则是Restricted Cone NAT，同时继续检测，go 7  
7.client向SN1发送3号包，让SN1换用另一个端口发4号包，重复若干次，如果client能收到说明  
是Restricted Cone NAT，否则是Port Restricted Cone NAT。检测结束。  
\*///////////////////////////////////////////////////////////////////////////////////////  
//读取第一个SN，SN1的(IP,Port)，并给其发0号包  
if(getSNfromHostCache(fp,snIP\[0],snPort\[0])==0)  
{  
printf("\[error]there is no SN in HostCache.txt!\\n");  
return 0;  
}  
/*  
int sendNCPtoSNandRecvNCP(unsigned long int ip\_SN,  
unsigned short int port\_SN,  
char version,  
char dowhat,  
unsigned long int ip,  
unsigned short int port)  
\*/  
ncp\_send.dowhat=0;  
ncp\_send.ip=0;  
ncp\_send.port=0;  
while(sendNCPtoSNandRecvNCP(snIP\[0],snPort\[0],ncp\_send)==0)  
{  
if(getSNfromHostCache(fp,snIP\[0],snPort\[0])==0)  
{  
printf("\[error]there is no more SN in HostCache.txt!\\n");  
//此时应该从中心节点获取更新的SN列表  
//......  
printf("\[error]check failed temporarily");  
return 0;  
}  
}  
long ft=ftell(fp);  
in\_addr\_tmp.S\_un.S\_addr=snIP\[0];  
printf("\[info]SN1 ip=%s\\tport=%d\\n",inet\_ntoa(in\_addr\_tmp),snPort\[0]);  
//对比返回的(ip,port) ip\_return port\_return  
unsigned long int ip\_return=((NCP \*)buff)-&gt;ip;  
unsigned short int port\_return=((NCP \*)buff)-&gt;port;  
if(myPriIp==ip\_return && myPriPort==port\_return)  
{  
printf("\[Reslut]public net\\n");  
myNetType=0;  
ncp\_send.dowhat=9;  
ncp\_send.ip=myPubIp=myPriIp;  
ncp\_send.port=myPubPort=myPriPort;  
broadcastNatCheckResult(ncp\_send);  
return 0;  
}  
//再读取一个SN，SN2的(IP,Port)  
int checkTime=N\_CheckTime;  
while(checkTime&gt;0 && !feof(fp))  
{  
if(getSNfromHostCache(fp,snIP\[1],snPort\[1])==0)  
{  
printf("\[error]there is no more SN in HostCache.txt!\\n");  
break;  
}  
ncp\_send.dowhat=1;  
ncp\_send.ip=snIP\[1];  
ncp\_send.port=snPort\[1];  
if(sendNCPtoSNandRecvNCP(snIP\[0],snPort\[0],ncp\_send)==1)  
{  
printf("\[Reslut]full cone nat\\n");  
myNetType=1;  
ncp\_send.dowhat=10;  
ncp\_send.ip=myPriIp;  
ncp\_send.port=myPriPort;  
myPubIp=ip\_return;  
myPubPort=port\_return;  
broadcastNatCheckResult(ncp\_send);  
return 0;  
}  
checkTime--;  
}  
printf("\[Reslut]not full cone nat, checking is continued.\\n");  
in\_addr\_tmp.S\_un.S\_addr=snIP\[1];  
printf("\[info]SN2 ip=%s\\tport=%d\\n",inet\_ntoa(in\_addr\_tmp),snPort\[1]);  
//在hostcache中的SN1下再找一个SN3，给他发送2号包，让他返回client的ip和port  
fseek(fp,ft,0);  
if(getSNfromHostCache(fp,snIP\[1],snPort\[1])==0)  
{  
printf("\[error]there is no SN in HostCache.txt!\\n");  
return 0;  
}  
ncp\_send.dowhat=2;  
ncp\_send.ip=0;  
ncp\_send.port=0;  
while(sendNCPtoSNandRecvNCP(snIP\[1],snPort\[1],ncp\_send)==0)  
{  
if(getSNfromHostCache(fp,snIP\[1],snPort\[1])==0)  
{  
printf("\[error]there is no more SN in HostCache.txt!\\n");  
//此时应该从中心节点获取更新的SN列表  
//......  
printf("\[error]check failed temporarily");  
return 0;  
}  
}  
in\_addr\_tmp.S\_un.S\_addr=snIP\[1];  
printf("\[info]SN3 ip=%s\\tport=%d\\n",inet\_ntoa(in\_addr\_tmp),snPort\[1]);  
//对比返回的(ip,port) ip\_return port\_return  
unsigned long int ip\_return1=((NCP \*)buff)-&gt;ip;  
unsigned short int port\_return1=((NCP \*)buff)-&gt;port;  
if(ip\_return1!=ip\_return || port\_return1!=port\_return)  
{  
printf("\[Reslut]symmetric nat\\n");  
myNetType=2;  
ncp\_send.dowhat=11;  
ncp\_send.ip=myPriIp;  
ncp\_send.port=myPriPort;  
broadcastNatCheckResult(ncp\_send);  
return 0;  
}  
ncp\_send.dowhat=3;  
ncp\_send.ip=0;  
ncp\_send.port=0;  
if(sendNCPtoSNandRecvNCP(snIP\[0],snPort\[0],ncp\_send)==1)  
{  
printf("\[Reslut]Restricted Cone nat\\n");  
myNetType=3;  
ncp\_send.dowhat=12;  
ncp\_send.ip=myPriIp;  
ncp\_send.port=myPriPort;  
myPubIp=ip\_return;  
myPubPort=port\_return;  
broadcastNatCheckResult(ncp\_send);  
return 0;  
}  
printf("\[Reslut]Port Restricted Cone nat\\n");  
myNetType=4;  
ncp\_send.dowhat=13;  
ncp\_send.ip=myPriIp;  
ncp\_send.port=myPriPort;  
myPubIp=ip\_return;  
myPubPort=port\_return;  
broadcastNatCheckResult(ncp\_send);  
//以上检测网络类型结束，下面开始与某好友通讯  
printf("do you want to talk with someone? \[Y]yes \[N]no\\n");  
scanf("%c",&ch);  
if(ch!='Y' && ch!='y')  
return 0;  
printf("which friend would you want to talk with? Input his id:\\n");  
scanf("%d",&friendID);  
//从SN1获取friend网络类型列表  
ncp\_send.dowhat=14;  
ncp\_send.ip=0;  
ncp\_send.port=0;  
ncp\_send.id=friendID;  
if(sendNCPtoSNandRecvNIRP(snIP\[0],snPort\[0],ncp\_send)==0)  
{  
printf("\[error]查询好友网络信息失败！\\n");  
return 0;  
}  
switch(friendNetType)  
{  
case 9:  
break;  
case 10:  
break;  
case 11:  
break;  
case 12:  
break;  
case 13:  
break;  
default:  
break;  
}  
}  
////////////////////////////////////////////////////////////////////  
//服务端程序入口  
/////////////////////////////////////////////////////////////////////  
else if(strcmp(argv\[1],"-s")==0)  
{  
//创建另一个套接字  
SOCKET sServer1;  
if( (sServer1 = socket(AF\_INET, SOCK\_DGRAM, IPPROTO\_UDP)) &lt; 0)  
{  
printf("获取SOCKET号失败!!!\\n");  
return 0;  
}  
//绑定套接字和本机地址和端口  
sn1\_addr.sin\_family=AF\_INET;  
sn1\_addr.sin\_port=htons(PORT\_SERVER\_NATCHECK\_1);  
sn1\_addr.sin\_addr.s\_addr =INADDR\_ANY ;//inet\_addr(getownIP()); //  
if(bind(sServer1, (struct sockaddr\*)&sn1\_addr, sizeof(sn1\_addr)) &lt; 0 )  
{  
printf("不能将服务器地址捆绑到SOCKET号上!!!\\n");  
closesocket(sServer1);  
return 0;  
}  
//////////////////  
// 循环队列natCheckRequestQueue初始化  
for(i=0;i&lt;N\_NatCheckRequestQueue-1;i++)  
{  
natCheckRequestQueue\[i].next= & natCheckRequestQueue\[i+1];  
}  
natCheckRequestQueue\[N\_NatCheckRequestQueue-1].next  
\= & natCheckRequestQueue\[0];  
h\_NatCheckRequestQueue = & natCheckRequestQueue\[0];  
t\_NatCheckRequestQueue = & natCheckRequestQueue\[0];  
//////////////////  
// 启动接受请求的服务线程  
// 入口函数为：ThreadFunction\_sn\_get  
// 判断队列是否满，不满的条件下，先修改t，再写进t指向的单元  
//HANDLE thread\_sn\_get = (HANDLE)\_beginthread(ThreadFunction\_sn\_get,0,NULL);  
HANDLE thread\_sn\_get = (HANDLE)\_beginthreadex(0,0,&ThreadFunction\_sn\_get,0,0,NULL);  
//////////////////  
// 主服务线程  
// 用来从循环队列natCheckRequestQueue的头指针得到请求数据来处理  
// 判断队列是否空，非空的条件下，先读出h指向的单元，再修改h  
while(1)  
{  
//判断队列是否空  
if(t\_NatCheckRequestQueue!=h\_NatCheckRequestQueue)  
{  
//先读出  
NCP * ncp\_deal=(NCP \*)buff;  
\*(ncp\_deal)=h\_NatCheckRequestQueue-&gt;ncp;  
unsigned long int ip\_deal=h\_NatCheckRequestQueue-&gt;ip;  
unsigned short int port\_deal=h\_NatCheckRequestQueue-&gt;port;  
//再修改h  
h\_NatCheckRequestQueue=h\_NatCheckRequestQueue-&gt;next;  
//处理这个来自(ip,port)的请求  
switch(ncp\_deal-&gt;dowhat)  
{  
/* dowhat字段：  
\* 0 请求用户返回Ip：port7 单独的响应包  
\* 1 客户请求提供其他主机检测6 其他主机响应包  
\* 2 同时请求两主机发回响应5 针对2的回应包  
\* 3 请求使用另一端口发回响应4 使用另一端口响应  
\* 8 SN请求其他主机检测  
\-----------------------------------------------------------  
\*9 汇报检测结果给SN public net  
\*10 汇报检测结果给SN full cone nat  
\*11 汇报检测结果给SN symmetric nat  
\*12 汇报检测结果给SN restricted cone nat  
\*13 汇报检测结果给SN port restricted cone nat  
\-----------------------------------------------------------  
\*/  
case 0:  
ncp\_deal-&gt;dowhat=7;  
ncp\_deal-&gt;ip=ip\_deal;  
ncp\_deal-&gt;port=port\_deal;  
client\_addr\_deal.sin\_family=AF\_INET;  
client\_addr\_deal.sin\_addr.S\_un.S\_addr=ip\_deal;  
client\_addr\_deal.sin\_port=port\_deal;  
printf("\[deal]\[0]send \[7] to:%d.%d.%d.%d:%d\\n",  
client\_addr\_deal.sin\_addr.S\_un.S\_un\_b.s\_b1,  
client\_addr\_deal.sin\_addr.S\_un.S\_un\_b.s\_b2,  
client\_addr\_deal.sin\_addr.S\_un.S\_un\_b.s\_b3,  
client\_addr\_deal.sin\_addr.S\_un.S\_un\_b.s\_b4,  
htons(client\_addr\_deal.sin\_port));  
sendto(sServer,buff,sizeof(buff),0,(sockaddr\*)&client\_addr\_deal,sizeof(client\_addr\_deal));  
break;  
case 1:  
client\_addr\_deal.sin\_family=AF\_INET;  
client\_addr\_deal.sin\_addr.S\_un.S\_addr=ncp\_deal-&gt;ip;  
client\_addr\_deal.sin\_port=htons(ncp\_deal-&gt;port);  
ncp\_deal-&gt;dowhat=8;  
ncp\_deal-&gt;ip=ip\_deal;  
ncp\_deal-&gt;port=port\_deal;  
printf("\[deal]\[1]send \[8] to:%d.%d.%d.%d:%d\\n",  
client\_addr\_deal.sin\_addr.S\_un.S\_un\_b.s\_b1,  
client\_addr\_deal.sin\_addr.S\_un.S\_un\_b.s\_b2,  
client\_addr\_deal.sin\_addr.S\_un.S\_un\_b.s\_b3,  
client\_addr\_deal.sin\_addr.S\_un.S\_un\_b.s\_b4,  
htons(client\_addr\_deal.sin\_port));  
sendto(sServer,buff,sizeof(buff),0,(sockaddr\*)&client\_addr\_deal,sizeof(client\_addr\_deal));  
break;  
case 2:  
client\_addr\_deal.sin\_family=AF\_INET;  
client\_addr\_deal.sin\_addr.S\_un.S\_addr=ip\_deal;  
client\_addr\_deal.sin\_port=port\_deal;  
ncp\_deal-&gt;dowhat=5;  
ncp\_deal-&gt;ip=ip\_deal;  
ncp\_deal-&gt;port=port\_deal;  
printf("\[deal]\[2]send \[5] to:%d.%d.%d.%d:%d\\n",  
client\_addr\_deal.sin\_addr.S\_un.S\_un\_b.s\_b1,  
client\_addr\_deal.sin\_addr.S\_un.S\_un\_b.s\_b2,  
client\_addr\_deal.sin\_addr.S\_un.S\_un\_b.s\_b3,  
client\_addr\_deal.sin\_addr.S\_un.S\_un\_b.s\_b4,  
htons(client\_addr\_deal.sin\_port));  
sendto(sServer,buff,sizeof(buff),0,(sockaddr\*)&client\_addr\_deal,sizeof(client\_addr\_deal));  
break;  
case 3:  
client\_addr\_deal.sin\_family=AF\_INET;  
client\_addr\_deal.sin\_addr.S\_un.S\_addr=ip\_deal;  
client\_addr\_deal.sin\_port=port\_deal;  
ncp\_deal-&gt;dowhat=4;  
ncp\_deal-&gt;ip=ip\_deal;  
ncp\_deal-&gt;port=port\_deal;  
printf("\[deal]\[3]send \[4] to:%d.%d.%d.%d:%d\\n",  
client\_addr\_deal.sin\_addr.S\_un.S\_un\_b.s\_b1,  
client\_addr\_deal.sin\_addr.S\_un.S\_un\_b.s\_b2,  
client\_addr\_deal.sin\_addr.S\_un.S\_un\_b.s\_b3,  
client\_addr\_deal.sin\_addr.S\_un.S\_un\_b.s\_b4,  
htons(client\_addr\_deal.sin\_port));  
sendto(sServer1,buff,sizeof(buff),0,(sockaddr\*)&client\_addr\_deal,sizeof(client\_addr\_deal));  
break;  
case 8:  
ncp\_deal-&gt;dowhat=6;  
client\_addr\_deal.sin\_family=AF\_INET;  
client\_addr\_deal.sin\_addr.S\_un.S\_addr=ncp\_deal-&gt;ip;  
client\_addr\_deal.sin\_port=htons(ncp\_deal-&gt;port);  
ncp\_deal-&gt;ip=getownIP\_uli();  
ncp\_deal-&gt;port=htons(PORT\_SERVER\_NATCHECK);  
printf("\[deal]\[8] send\[6] to:%d.%d.%d.%d:%d\\n",  
client\_addr\_deal.sin\_addr.S\_un.S\_un\_b.s\_b1,  
client\_addr\_deal.sin\_addr.S\_un.S\_un\_b.s\_b2,  
client\_addr\_deal.sin\_addr.S\_un.S\_un\_b.s\_b3,  
client\_addr\_deal.sin\_addr.S\_un.S\_un\_b.s\_b4,  
htons(client\_addr\_deal.sin\_port));  
sendto(sServer,buff,sizeof(buff),0,(sockaddr\*)&client\_addr\_deal,sizeof(client\_addr\_deal));  
break;  
case 9:  
//写入id 网络类型 外网ip port 内网ip port  
storeNatCheckResult(ncp\_deal-&gt;id,  
ncp\_deal-&gt;dowhat,ip\_deal,port\_deal,  
ncp\_deal-&gt;ip,ncp\_deal-&gt;port);  
printf("\[deal]\[9] writing file\\n");  
break;  
case 10:  
//写入id 网络类型 外网ip port 内网ip port  
storeNatCheckResult(ncp\_deal-&gt;id,  
ncp\_deal-&gt;dowhat,ip\_deal,port\_deal,  
ncp\_deal-&gt;ip,ncp\_deal-&gt;port);  
printf("\[deal]\[10] writing file\\n");  
break;  
case 11:  
//写入id 网络类型 外网ip port 内网ip port  
storeNatCheckResult(ncp\_deal-&gt;id,  
ncp\_deal-&gt;dowhat,ip\_deal,port\_deal,  
ncp\_deal-&gt;ip,ncp\_deal-&gt;port);  
printf("\[deal]\[11] writing file\\n");  
break;  
case 12:  
//写入id 网络类型 外网ip port 内网ip port  
storeNatCheckResult(ncp\_deal-&gt;id,  
ncp\_deal-&gt;dowhat,ip\_deal,port\_deal,  
ncp\_deal-&gt;ip,ncp\_deal-&gt;port);  
printf("\[deal]\[12] writing file\\n");  
break;  
case 13:  
//写入id 网络类型 外网ip port 内网ip port  
storeNatCheckResult(ncp\_deal-&gt;id,  
ncp\_deal-&gt;dowhat,ip\_deal,port\_deal,  
ncp\_deal-&gt;ip,ncp\_deal-&gt;port);  
printf("\[deal]\[13] writing file\\n");  
break;  
case 14:  
//处理client发来的查询请求  
//查询id对应用户的网络信息  
client\_addr\_deal.sin\_family=AF\_INET;  
client\_addr\_deal.sin\_addr.S\_un.S\_addr=ip\_deal;  
client\_addr\_deal.sin\_port=port\_deal;  
printf("\[deal]\[14]send \[15] to:%d.%d.%d.%d:%d\\n",  
client\_addr\_deal.sin\_addr.S\_un.S\_un\_b.s\_b1,  
client\_addr\_deal.sin\_addr.S\_un.S\_un\_b.s\_b2,  
client\_addr\_deal.sin\_addr.S\_un.S\_un\_b.s\_b3,  
client\_addr\_deal.sin\_addr.S\_un.S\_un\_b.s\_b4,  
htons(client\_addr\_deal.sin\_port));  
searchNatCheckResult(\*ncp\_deal,sServer,client\_addr\_deal);  
break;  
default:  
break;  
}  
}  
Sleep(300);  
}  
}  
//////////////////  
// 终止 Windows sockets API  
WSACleanup();  
return 0;  
}