44
Network Programming Using Internet Sockets Wu Xuanxuan Lai Xinyu 吴璇璇 赖新宇 [email protected] [email protected]

Network Programming Using Internet Sockets - cs.tju.edu.cncs.tju.edu.cn/faculty/zenghua/Network_2013/Socket_Programming... · Basic Socket Programming •What is a Socket –Definition

Embed Size (px)

Citation preview

Network Programming Using Internet Sockets

Wu Xuanxuan Lai Xinyu 吴璇璇 赖新宇

[email protected] [email protected]

Agenda

• Basic Socket Programming

– Understanding Sockets

– Socket API

– Structs and Data Handling

– A simple example

• Assignment

• References

Basic Socket Programming

• What is a Socket

– Definition 1:

• A door between application process and end-end transport protocol(TCP/UDP)

– Definition 2:

• A way to speak to other programs using standard UNIX file descriptors.

– Definition 3:

• An endpoint in communication

• Definition 1: a door between application process and end-end transport protocol (TCP/UDP)

Basic Socket Programming

Understanding Sockets- Definition 1

Basic Socket Programming Understanding Sockets-Definition1

controlled by app developer

Controlled by OS

You write sockets programs without knowing how the lower levels‘ protocols works!

loosely-coupled

Basic Socket Programming

Understanding Sockets- Definition1

Socket API: (1) choice of transport protocol;

(2) ability to fix a few parameters

• Two types of transport service via Internet socket API: – Stream Sockets (connection-oriented )

• They use TCP (Transmission Control Protocol) protocol – Reliable stream

– Datagram Sockets (connectionless) • They use UDP (User Datagram Protocol) protocol

– Unreliable datagram

• Definition2: a way to speak to other programs

using standard Unix file descriptors.

Basic Socket Programming

Understanding Sockets- Definition 2

• Socket Programming int sockfd; /*socket descriptor*/

sockfd= socket( AF_INET, SOCK_STREAM, 0);

read( sockfd, … );

• File Operation char buf[100];

int fd; /*file descriptor*/

fd= open(“foo", O_RDONLY);

read( fd, buf, num_bytes);

Basic Socket Programming

Understanding Sockets- Definition2

• Definition3: merely an endpoint in communication.

Basic Socket Programming

Understanding Sockets- Definition 3

Basic Socket Programming

Understanding Sockets- Definition 3

– IP:User needs to know the IP ADDRESS of the server.

– Port number: On the server, many processes are running. We want to “talk” to the right one.

• The knowledge of the IP addresses and the Port Number define uniquely a communication endpoint.

Basic Socket Programming

Socket API-TCP Model

Basic Socket Programming

Socket API-UDP Model

Server: No bind() and accept().

Client: No connect().

Basic Socket Programming

Socket API-socket() • socket() -Get the File Descriptor!

– The first step is to require the OS to reserve one “descriptor” for the communication channel.

int sockfd = socket(AF_INET, socket_type, 0); /*socket_type=SOCK_STREAM|SOCK_DGRAM*/

/*AF_INET means we use IP (version 4)*/

/*0 is for IP (not ICMP or others)*/

/*return a socket descriptor or -1 when error*/

Protocol Family Symbolic Name TCP/IP Internet AF_INET Xerox NS AF_NS Intra-host Unix AF_UNIX DEC DNA AF_DECNET

Service Type symbolic name datagram (UDP) SOCK_DGRAM reliable, in order (TCP) SOCK_STREAM raw socket SOCK_RAW

If(sockfd < 0)

perror(“can’t create socket");

Basic Socket Programming

Socket API-bind()

• bind()-What IP address and port am I on? struct sockaddr_in servaddr; bind(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr));

Note:

– Only the server need to call this API;

– The type of the second parameter should be sockaddr while we often use sockaddr_in in the program——Type Conversation

• close(sockfd);

– frees up any memory associated with the socket

• shutdown(sockfd, how);

/* how = 0 -> disable receptions */

/* how = 1 -> disable transmission */

/* how = 2 -> the same as close() */

Basic Socket Programming

Socket API-close(),shutdown()

Basic Socket Programming

TCP API(SERVER)-listen()

• listen()-Who will call me? listen(sockfd, req_no);

• req_no: specifies the maximum number of client connections that the kernel will queue for this listening descriptor.

• accept()-Thank you for calling port 3490. int new_sd, sockfd, size;

struct sockaddr remote_addr;

new_sd = accept(sockfd, &remote_addr, &size);

– If the queue is empty, the process will be blocked. – If so, accept() returns a NEW SOCKET DESCRIPTOR ! – the old socket descriptor (sockfd) is still queuing request from the

network ! – So, if we want to communicate with the client, we MUST use new_sd.

– new_sd is a socket ready for the communication – It is suggested that handle new_sd in a child process or a thread.

Basic Socket Programming

TCP API(SERVER)-accept()

Basic Socket Programming

TCP API(CLIENT)-connect()

• connect()-Hey, you! int sockfd; connect(sockfd, (sockaddr*) &servaddr, sizeof(servaddr) );

– On the client side, bind is done automatically – The local IP address is the one provided by default – A port “randomly” assigned by the operating system is good. – So, we put in servaddr the information on the server and try to

connect to it. – Finish three-way handshake

Basic Socket Programming

TCP API-send() , recv() • send() and recv() -Talk to me, baby!

int send(int sockfd, const void *msg, int len, int flags);

int recv(int sockfd, void *buf, int len, unsigned int flags);

char *msg = “Hi, baby!";

char buffer[SOME_SIZE];

int len, nset, nrecv; .

.

len = strlen(msg);

nset= send(sockfd, msg, len, 0);

.

nrecv = recv(sockfd, &buffer, len, flags)

Basic Socket Programming

TCP API-read() , write() • read() and write() –more choices

• read() = recv(*, *, *, 0)

• write() = send(*, *, *, 0)

• Programmers are familiar with, similar to file operations

• recv() and send() • explicit meaning

Basic Socket Programming

UDP API-sendto() , recvfrom()

• sendto() and recvfrom() int sendto(int sockfd, const void *msg, int len, unsigned int flags, const struct sockaddr *to, int tolen);

int recvfrom(int sockfd, void *buf,int len,unsigned int flags, struct sockaddr *from, int *fromlen)

– Send directly without handshake

– The first four parameters are the same with send/recv

– to/from is a pointer to a struct sockaddr which contains the destination IP address and port.

– tolen/fromlen, can simply be set to sizeof(struct sockaddr).

Basic Socket Programming

Structs and Data Handling-IP address

• IP Address – Every host has a unique IP Address – 32bits

• Three forms – hostname (string) e.g. localhost – dotted decimal(string) e.g. 192.168.2.1 – binary(u_long)

• Dealing with them inet_addr() : dotted decimal to binary

gethostbyname() : hostname to binary

e.g. servaddr.sin_addr.s_addr =inet_addr(“59.67.33.68");

Basic Socket Programming

Structs and Data Handling-Port

• Port – 1-255 reserved for standard services

– 21 ftp

– 23 telnet

– 25 SMTP

– 80 HTTP

– 1-1023 Available only to priviledged users

– 1024-4999 Usuable by system and user processes

– 5000- Usuable by user processes only

Basic Socket Programming

Structs and Data Handling-struct sock_addr

• struct sockaddr :This structure holds socket address information for many types of sockets:

• struct sockaddr { unsigned short sa_family; // address family, AF_xxx char sa_data[14]; // 14 bytes of protocol address

};

• sockaddr is the structure with the addresses and the ports. We put IP address and the Port in sa_data[14].

Not convenient to deal with?

Basic Socket Programming

Structs and Data Handling-struct sockaddr_in • struct sockaddr_in:To deal with sockaddr, programmers

created a structure: struct sockaddr_in ("in" for "Internet".) • struct sockaddr_in {

short int sin_family; // Address family unsigned short int sin_port; // Port number struct in_addr sin_addr; // Internet address unsigned char sin_zero[8]; // Same size as struct sockaddr

};

• struct in_addr{ /* 32-byte IP Address *./

in_addr_t s_addr;

};

We can work with sockaddr_in and cast it to sockaddr.

struct sockaddr_in servaddr; bind(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr));

Basic Socket Programming

Structs and Data Handling

• Convert the Natives! • Know this:

– there are two byte orderings

• most significant byte first-“Network Byte Order” (NBO).

• or least significant byte first-"Host Byte Order” (HBO).

– htons() host to network short

– htonl() host to network long

– ntohs() network to host short

– ntohl() network to host long

• e.g. servaddr.sin_addr.s_addr = htonl(INADDR_ANY); /*IP address of localhost*/

servaddr.sin_port = htons(13);

Basic Socket Programming

Structs and Data Handling

• And here's a sample, while packing a struct sockaddr_in /* an Internet endpoint address*/

struct sockaddr_in my_addr; my_addr.sin_family = AF_INET; /* host byte order */

my_addr.sin_port = htons(MYPORT); /* short, NBO*/

my_addr.sin_addr.s_addr = inet_addr("132.241.5.10");

bzero(&(my_addr.sin_zero)); /* zero the rest of the struct */

Basic Socket Programming

a simple example-TCP server

Basic Socket Programming

a simple example-TCP client

Basic Socket Programming a simple example- Result

• P2P Principle login search share logout ping download

P2P Server

Peer Client Peer Client

Programming Assignment

Assignment

• Phase1: Establishing Client-Server Communications

(Mandatory; 60 points)

• Phase2: Establishing Peer-Peer Communications

(Mandatory; 40 points Optional; 20 points)

Phase1: Establishing Client-Server Communications -- Mandatory

• 1) Authenticate with the server (provide a username and encrypted password)

• 2) Send a list of files to the server that you wish to share with other users

• 3) Submit a search query to the server for a file you wish to download

• 4) Receive the search results, parse them, and output them to the user

• 5) Log out

Phase1: Authenticate

• Protocol packet

packet head is 4 bytes!

Phase1: Share

• Protocol packet:

Phase1: Search

• Protocol packet:

Phase1: Logout

• Protocol packet:

Phase2: Establishing Peer-Peer Communications

• 1) Add functionality to send "ping" messages over UDP and listen for echo responses, in order to estimate the round trip time to another peer. --Mandatory

• 2) Add functionality to respond to ping messages from other peers.-- Mandatory

• 3) Add functionality to connect to another peer and download a file.

• 4) Add functionality to make your peer a file server, so that other peers may connect and download files from you.

Phase2: Ping

• Send UDP Ping Message.

• Protocol packet:

Do not guarantee delivery of packets!

Use timeout control—select()

Phase2: Peer-Peer Communications

• Protocol packet:

No need password!

Phase2: Peer-Peer Communications (cont...)

• Protocol packet:

Requirement

• Program Correctness and Functionality: 60%

• Code design & Program Structure: 10%

• Documentation: 30%

Deadline

• Mandatory : April 27

• Optional: May 7

• Submit to: [email protected]

• For more detail: detailed requirements.pdf

References

• Warren W. Gay , “Linux Socket Programming by Example”

• Beej's Guide to Network Programming Using Internet Sockets

• Douglas E. Comer, David L. Stevens, “Internetworking With TCP/IP Vol III”

Thank you!