TCP Hits the Hole

Source: Internet
Author: User
Tags assert prepare server port

The rapid development of the Internet and the limitation of the number of IPV4 addresses make network address translation (Nat,network addresses trans2lation) devices widely used. NAT devices allow multiple hosts to share a public network after the same NAT (this article will be in the same NAT network called private network, in front of the NAT network called Public network) IP address. A private network IP address communicates with other hosts on the public network through a NAT device. Public and private network IP address domain, as shown in the following figure:

The sketch of WAN and private network

In general, private network host (such as the "Computer A-01") initiative to initiate a connection, the packet after the NAT address translation sent to the public network server (such as the "server" in the above), the connection is established after the two-way transmission of data, NAT devices allow private network host to send data to the public network host actively, but the reverse direction of the active transmission, but in a number of special occasions in different private network host to interconnect (such as Peer-to-peer software, network conferencing, video transmission, etc.), TCP through the NAT problem must be resolved. The internet about UDP through the NAT article a lot of, but also have matching source code, but I personally think that although the UDP data speed, but there is no guarantee, and NAT for UDP prepared temporary port number has life cycle limit, not easy to use, TCP connections are preferred on applications that require quality of transmission (for example, file transfers).

There are a lot of internet about TCP through NAT (that is, TCP hole) introduction article, but unfortunately I have not found the relevant source code can refer to, I use the free time to write a TCP through the NAT, so that different private network within the host to establish direct TCP communication sources.

Here is a description of the type of NAT:

The type of NAT device has a very important influence on TCP traversing NAT, according to the port mapping method, Nat can be divided into 4 categories, the first 3 NAT types can be collectively referred to as cone types.

(1) Full Cone: NAT maps all requests from the same internal IP address and port to the same external IP address and port. Any external host can send IP packets to the internal host through this mapping.

(2) Restrictive cloning (restricted Cone): NAT maps all requests from the same internal IP address and port to the same external IP address and port. However, the external host can send IP packets to the internal host only if the internal host sends IP packets first to an external host with an IP address of x.

(3) Port restrictive cloning (port restricted Cone): Ports restrictive cloning is similar to restrictive cloning, but only the limit of the port number, that is, only the internal host first to the IP address x, the port number for the external host of p to send 1 IP packets, The external host is able to send the IP packet of the source port number p to the internal host.

(4) Symmetric NAT (symmetric NAT): This type of NAT differs from the above 3 types in that when the same internal host uses the same port to communicate with an external host of different addresses, the NAT's mapping to that internal host differs. Symmetric NAT does not guarantee the consistency of bindings between private addresses and exposed IP in all sessions. Instead, it assigns a new port number to each new session.

Let's assume first: there is a server s on the public network has an IP, two private networks by Nat-a and Nat-b connected to the public network, nat-a behind a client a,nat-b behind a client B, now, we need to use s to establish a and B direct TCP connection, That is, a hole from B to a, so that a can be connected directly to the B host in the hole, as if Nat-b does not exist.

The implementation process is as follows (please refer to the source code):

1, S starts two network listens, one is called "The main connection" listens, one is called "assists the hole" the interception.

2, A and B are in contact with S "main connection" respectively.

3. When a needs to establish a direct TCP connection with B, first connect the "Help hole" port of S, and send the assist connection application. At the same time, start listening on the port number. Note Because you have to bind to different sockets on the same network terminal, you must set the So_reuseaddr property for these sockets (that is, allow reuse), or the listener will fail.

4, S "Assistance hole" connection received a application after the "Primary connection" notification B, and a after Nat-a converted public network IP address and port information to tell B.

5, B received the connection of S after the first and the "Help hole" port connection, random send some data immediately after the disconnect, the purpose is to let S know b after nat-b converted public network IP and port number.

6, B try to connect with a after nat-a conversion of the public IP address and the port, according to different routers will have different results, some routers in this operation can establish a connection (for example, I used Tplink R402), Most routers fail to connect by simply discarding the SYN request package, but NAT-A will record the connection's source address and port number and prepare for the next real connection, which is called a hole, that is, B to a hole, The next time a will be able to connect directly to the port number that B just used.

7, Client B hole at the same time on the same port to start listening. B After everything is ready through the "Master Connection" reply message "I am ready" with S, s after receiving the B after nat-b conversion of the public network IP and port number to a.

8, a received s reply to B's public IP and port number, etc. start connecting to B public IP and port number, because in step 6 B has tried to connect the public IP address and port of a, nat-a record this connection information, so when a active connection B, Nat-b would be considered legitimate SYN data and allowed to pass through, thus direct TCP connections were established.

The entire implementation process by writing I am afraid it is difficult to speak clearly, coupled with my language ability is very poor (college entrance examination of the Chinese only 75 points, total score of 150 points, ashamed), so have to use the code to explain the problem.

server address and port number definition

#define SRV_TCP_MAIN_PORT 4000//server host connection port number

#define SRV_TCP_HOLE_PORT 8000/server port number in response to client hole request

The two ports are fixed and the server S starts listening on both ports. Sendnewuserloginnotify (Lpszclientip, Nclientport, Dwid))

{

G_csfor_ptrary_sockclient.unlock ();

return FALSE;

}

}

}

G_csfor_ptrary_sockclient.unlock ();

return TRUE;

}

When a new client connects to the server, the server is responsible for sending the client's information (IP address, port number) to other clients. 0)

{

ASSERT (nrecvbytes = = sizeof (T_SRVREQDIRECTCONNECTPKT));

Packet_type *pepackettype = (packet_type*) szrecvbuffer;

ASSERT (pepackettype && *pepackettype = = Packet_type_tcp_direct_connect);

Sleep (1000);

Handle_srvreqdirectconnect ((t_srvreqdirectconnectpkt*) szrecvbuffer);

printf ("Handle_srvreqdirectconnect end/n");

}

The other is disconnected.

Else

{

Goto finished;

}

BRet = TRUE;

Finished:

G_psock_makehole = NULL;

return bRet;

}

This assumes that client a starts first, client A will receive a notification of the new client login of server s after Client B starts and receive the public IP and port of client B, and client a initiates a thread connecting S to the "Help Hole" port (the local port number can be obtained using the Getsocketname () function). Assuming m), ask S to assist TCP in the hole, and then start the thread to listen for the connection request on the local port (previously assumed m) and wait for the server to respond. Sendchunk (&srvreqmakeholepkt, sizeof (T_SRVREQMAKEHOLEPKT), 0)!= sizeof (T_SRVREQMAKEHOLEPKT))

return FALSE;

Wait for client B hole to finish, notify client after completion to direct connect client external IP and port number

if (! Handle_is_valid (M_hevtwaitclientbhole))

return FALSE;

if (WaitForSingleObject (m_hevtwaitclientbhole, 6000*1000) = = WAIT_OBJECT_0)

{

if (Sendchunk (&m_srvreqdirectconnectpkt, sizeof (T_SRVREQDIRECTCONNECTPKT), 0)

= = sizeof (T_SRVREQDIRECTCONNECTPKT))

return TRUE;

}

return FALSE;

}

The server s receives client A's assistance to punch a hole request to notify Client B, requiring client B to make a hole to client A, that is, let client B try to connect with client A's public network IP and port. Dwinvitedid;

if (Mainsock.send (&holelistenreadypkt, sizeof (T_HOLELISTENREADYPKT))!= sizeof (T_HOLELISTENREADYPKT))

{

printf ("Send holelistenreadypkt to%s:%u failed:%s/n",

G_welcomepkt.szclientip, G_welcomepkt.nclientport,

Hwformatmessage (GetLastError ()));

return FALSE;

}

return TRUE;

}

Client B receives a hole call from server S, first connect S to the "help Hole" port number (the local port number can be obtained using the Getsocketname () function, assuming x), the boot thread attempts to connect client A's public IP and port number, depending on the router, the connection is different, If the luck is good the direct connection succeeds, even if the connection fails, but the hole is completed. Also, start the thread to detect the connection on the same port (that is, the local port number x of the connection to the "Help hole" port number of s), waiting for client A to connect directly to the port number. Received Data:%s/n ", Szrecvbuffer);

memset (szrecvbuffer, 0, sizeof (szrecvbuffer));

Sleep_break (1);

}

Else

{

Sleep_break (300);

}

}

}

}

catch (CException e)

{

Char szerror[255] = {0};

E.geterrormessage (szerror, sizeof (szerror));

printf ("Exception occur,%s/n", szerror);

return FALSE;

}

return TRUE;

}

After client B holes and listen ready, the server S reply client A, client a directly with Client B's public network IP and port to connect, send and receive data can be normal, in order to test whether the real direct TCP connection, in the data transceiver can be forced to terminate the server S, See if the data sent and received is still normal.

Program execution steps and methods:

To prepare the environment, if you want to real test words need to use 2 to connect to the public network LAN, 1 with public network address of the computer (in order to help me test, small Cao, chick can be a lot of heart, I also commandeer their home computer, in this express thanks). If this is not the case, program execution may be abnormal because I do not have the same LAN processing for the time being.

In the public network address of the computer to execute the "TcpHoleSrv.exe" program, assuming this computer's public network IP address is "129.208.12.38".

Perform "Tcpholeclt-a.exe 129.208.12.38" on a single computer in LAN a

Perform "Tcpholeclt-b.exe 129.208.12.38" on a single computer in LAN B

After the successful implementation of the program interface: The client appears "Send data" or "Received data" means that the TCP connection across the NAT has been established, data delivery has been OK.

Server S

Client A

Client B

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.