int bind(int s, (struct sockaddr *)addr, int length)
s = socket variable
addr = a socket IP address structure
length = length of the socket IP address structure
|
Example:
int IPAddress; (a 32 bit IP address)
short PortNumber; (a 16 bit port number)
int s;
struct sockaddr_in in_addr;
s = socket(PF_INET, SOCK_DGRAM, 0); // Create UDP socket
/* --------------------------------
Set up Internet network address
-------------------------------- */
in_addr.sin_family = AF_INET; /* IP Protocol domain */
in_addr.sin_addr.s_addr = htonl(IPAddress); /* IP address */
in_addr.sin_port = htons(PortNumber); /* UDP port # */
/* --------------------------------
Bind socket to network address
-------------------------------- */
if ( bind(s, (struct sockaddr *)&in_addr, sizeof(in_addr)) != 0 )
perror("Bind error: ");
|
What does the program achieve:
|
Notes:
|
Example: (on W301 computer):
/* ------------------------------------------------------
Find W301's IP address in dotted decimal notation
------------------------------------------------------ */
cheung@W301(1007)> ifconfig
eth0 Link encap:Ethernet HWaddr 3C:D9:2B:76:D7:09
inet addr:170.140.151.25 Bcast:170.140.151.255 Mask:255.255.254.0
inet6 addr: fe80::3ed9:2bff:fe76:d709/64 Scope:Link
/* --------------------------------------
Convert IP address in binary
-------------------------------------- */
cheung@W301(1008)> bc
170*256*256*256 + 140*256*256 + 151*256 + 25
2861340441
/* --------------------------------------
Bind call with W301's IP address
-------------------------------------- */
cheung@W301(1011)> udp1 2861340441 8000
**** Bind was successful....
Socket is bind to:
addr = 2861340441
port = 8000
/* ----------------------------------------------------
ERROR test: Bind call with not-your-own IP address
---------------------------------------------------- */
cheung@W301(1010)> udp1 2861340442 8000
Error: bind to addr = 2861340442,, port = 8000 FAILED
Bind ?: Cannot assign requested address
|
|
|