1 Introduction to Unix Network Programming
Reference: Stevens Unix Network Programming
8/30/06 UIUC - CS/ECE 438, Fall 2006 2
How do we Communicate?
Send a mail from Alice to Bob
Alice in Champaign, Bob in Hollywood
Example:
US Postal Service
Bob Champaign, Illinois Hollywood, California Alice
8/30/06 UIUC - CS/ECE 438, Fall 2006 3
What does Alice do?
Bob’s address (to a mailbox)
Bob’s name – in case people share mailbox
Postage – have to pay!
Alice’s own name and address – in case Bob wants to return a message Bob 100 Santa Monica Blvd. Hollywood, CA 90028 Alice 200 Cornfield Rd. Champaign, IL 61820
8/30/06 UIUC - CS/ECE 438, Fall 2006 4
What does Bob do?
Install a mailbox
Receive the mail
Get rid of envelope
Read the message
Bob 100 Santa Monica Blvd. Hollywood, CA 90028 Alice 200 Cornfield Rd. Champaign, IL 61820
8/30/06 UIUC - CS/ECE 438, Fall 2006 5
What about sending a TCP/IP packet?
Very similar to Alice-mailing-to-Bob Different terminologies Different technologies
Suppose to be better (faster, more
reliable, cheaper, …)
8/30/06 UIUC - CS/ECE 438, Fall 2006 6
Two simplest networking programs
Alice
the sending process
Alice’s address: 128.174.246.177 (IP addr)
Alice’s name: 12345 (port #)
Bob
the receiving process
Bob’s address: 216.52.167.132 (IP addr)
Bob’s name: 23456 (port #)
int main () { int sockfd; struct sockaddr_in bob_addr, alice_addr; bzero(&bob_addr, sizeof(bob_addr)); bob_addr.sin_family = AF_INET; bob_addr.sin_addr.s_addr = 0xD834A784; bob_addr.sin_port = 23456; // do the same for alice_addr … sockfd = socket(AF_INET, SOCK_DGRAM, 0); sendto(sockfd, “hi”, strlen(“hi”), 0, &bob_addr, sizeof(bob_addr)); } int main () { int sockfd, n; struct sockaddr_in bob_addr, alice_addr; char mesg[100]; bzero(&bob_addr, sizeof(bob_addr)); bob_addr.sin_family = AF_INET; bob_addr.sin_addr.s_addr = 0xD834A784; bob_addr.sin_port = 23456; sockfd = socket(AF_INET, SOCK_DGRAM, 0); bind(sockfd, &bob_addr, sizeof(bob_addr)); n= recvfrom(sockfd, mesg, 100, 0, &alice_addr, sizeof(alice_addr)); }