Download presentation
Presentation is loading. Please wait.
Published byClifford Cunningham Modified over 9 years ago
1
Network Programming Using Internet Sockets Wu Xuanxuan Lai Xinyu 吴璇璇 赖新宇 xuan_tju@126.com 15122211137@163.com
2
Agenda Basic Socket Programming – Understanding Sockets – Socket API – Structs and Data Handling – A simple example Assignment References
3
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
4
Definition 1: a door between application process and end-end transport protocol (TCP/UDP) Basic Socket Programming Understanding Sockets- Definition 1
5
controlled by app developer Controlled by OS You write sockets programs without knowing how the lower levels‘ protocols works! loosely-coupled
6
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
7
Definition2: a way to speak to other programs using standard Unix file descriptors. Basic Socket Programming Understanding Sockets- Definition 2
8
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
9
Definition3: merely an endpoint in communication. Basic Socket Programming Understanding Sockets- Definition 3
10
– 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.
11
Basic Socket Programming Socket API-TCP Model
12
Basic Socket Programming Socket API-UDP Model Server: No bind() and accept(). Client: No connect().
13
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");
14
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
15
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()
16
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.
17
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()
18
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
19
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)
20
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
21
Basic Socket Programming UDP API-sendto(), recvfrom() sendto() and recvfrom() i nt 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).
22
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");
23
Basic Socket Programming Structs and Data Handling-Port Port – 1-255reserved for standard services – 21ftp – 23telnet – 25SMTP – 80HTTP – 1-1023Available only to priviledged users – 1024-4999Usuable by system and user processes – 5000-Usuable by user processes only
24
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?
25
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));
26
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);
27
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 */
28
Basic Socket Programming a simple example-TCP server
29
Basic Socket Programming a simple example-TCP client
30
Basic Socket Programming a simple example - Result
31
P2P Principle login search share logout ping download P2P Server Peer Client Programming Assignment
32
Assignment Phase1: Establishing Client-Server Communications (Mandatory; 60 points) Phase2: Establishing Peer-Peer Communications (Mandatory; 40 points Optional; 20 points)
33
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
34
Phase1: Authenticate Protocol packet packet head is 4 bytes!
35
Phase1: Share Protocol packet:
36
Phase1: Search Protocol packet:
37
Phase1: Logout Protocol packet:
38
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.
39
Phase2: Ping Send UDP Ping Message. Protocol packet: Do not guarantee delivery of packets! Use timeout control—select()
40
Phase2: Peer-Peer Communications Protocol packet: No need password!
41
Phase2: Peer-Peer Communications (cont...) Protocol packet:
42
Requirement Program Correctness and Functionality: 60% Code design & Program Structure: 10% Documentation: 30%
43
Deadline Mandatory : April 27 Optional: May 7 Submit to: cn_tju@163.com For more detail: detailed requirements.pdf
44
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!
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.