Environment:
Two NICs are in different network environments.
Lan 1: Gateway: 10.9.16.254
Computer address:. 9.16.88
Lan 2: Gateway: 10.9.24.1
Computer address:. 9.24.88
Requirement: Send a piece of data to 10.9.24.1 through 10.9.16.88.
CodeAs follows:
# Include "stdafx. H "# include <winsock2.h> # include <stdio. h> # pragma comment (Lib, "ws2_32.lib") # include <process. h> void udptest (); int _ tmain (INT argc, _ tchar * argv []) {udptest (); return 1;} void udptest () {word wversionrequested; wsadata; int err; wversionrequested = makeword (1, 1); err = wsastartup (wversionrequested, & wsadata); If (Err! = 0) {return;} If (lobyte (wsadata. wversion )! = 1 | hibyte (wsadata. wversion )! = 1) {wsacleanup (); return;} socket sockclient = socket (af_inet, sock_stream, 0); sockaddr_in addrself; // local address addrself. sin_addr.s_un.s_addr = inet_addr ("10.9.16.88"); // specify the network adapter address addrself. sin_family = af_inet; addrself. sin_port = htons (17557); If (-1 = BIND (sockclient, (sockaddr *) & addrself, sizeof (sockaddr ))) // forcibly bind the NIC address to socketprintf ("BIND error! \ R \ n "); socket sendtosocket = socket (af_inet, sock_dgram, ipproto_udp); printf (" BIND: % d \ r \ n ", BIND (sendtosocket, (sockaddr *) & addrself, sizeof (sockaddr); sockaddr_in addrsrv; addrsrv. sin_addr.s_un.s_addr = inet_addr ("10.9.24.1"); // sent to 10.9.24.1; addrsrv. sin_family = af_inet; addrsrv. sin_port = htons (17557); While (1) {char * pchsend = "abcdefghijklmn"; int I = sendto (sendtosocket, pchsend, strlen (pchsend), 0, (sockaddr *) & addrsrv, sizeof (sockaddr); printf ("sendto: % d \ r \ n", I); printf ("......... \ r \ n "); sleep (3000);} closesocket (sockclient); wsacleanup ();}
Note the following code:
Sockaddr_in addrself; // local address addrself. sin_addr.s_un.s_addr = inet_addr ("10.9.16.88"); // specify the network adapter address addrself. sin_family = af_inet; addrself. sin_port = htons (17557); If (-1 = BIND (sockclient, (sockaddr *) & addrself, sizeof (sockaddr ))) // forcibly bind the NIC address to socketprintf ("BIND error! \ R \ n ");
Generally, UDP does not need to bind an address to a socket. Only TCP needs to bind a port and an IP address.
If we do not run the BIND () function here, the system will send the packet sent to 10.9.24.1 through the network adapter 10.9.24.88 based on its own route.