0% found this document useful (0 votes)
7 views35 pages

Chapter 4

The document provides an overview of basic TCP and UDP socket programming, detailing the functions and processes involved in creating TCP clients and servers, as well as UDP communication. It includes code examples for socket creation, connection, data transmission, and handling client-server interactions. Additionally, it discusses exercises for practical implementation of TCP and UDP servers and clients, including broadcasting and file sharing functionalities.

Uploaded by

ngominh9499
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views35 pages

Chapter 4

The document provides an overview of basic TCP and UDP socket programming, detailing the functions and processes involved in creating TCP clients and servers, as well as UDP communication. It includes code examples for socket creation, connection, data transmission, and handling client-server interactions. Additionally, it discusses exercises for practical implementation of TCP and UDP servers and clients, including broadcasting and file sharing functionalities.

Uploaded by

ngominh9499
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 35

Basic TCP and UDP

Socket
School of Information and Communication Technology,
Hanoi University of Science and Technology
References
[1] W.Richard Stevens, Unix Network Programming Vol.1, 3rd Ed., Prentice
Hall.
[2] Keir Davis, John W. Turner, and Nathan Yocom, The Definitive Guide to
Linux Network Programming, Apress.
[3] Michael Donahoo, Kenneth Calvert, TCP/IP Sockets in C: Practical Guide
for Programmers, Elsevier.

2
Content
• Stream socket
• TCP Application
• Functions in client side
• Iterating TCP server

3
TCP Client
• Provide reliable client server
communication
• Data rate control SYN
• Example
• Mail SYN+ACK
• WEB
• Image ACK

Data

4
Example (TCP) TCP Server
socket()
TCP client
bind()
socket()
listen()
connect() establish
accept()

write() data
read()

data write()

read()
end read()
close()
close()

5
socket()
• #include <sys/types.h>
• #include <sys/socket.h>
• int socket(int domain, int type, int protocol)
• Return value:
• A new socket file descriptor (a socket “handle”) that you
can use to read/receive data from/to
• If error occurs, return -1
• The domain is AF_INET, AF_INET6, or AF_UNSPEC, etc.
• The type argument can be:
• SOCK_STREAM: socket for TCP connection
• SOCK_DGRAM: Socket for datagram communication (UDP)
• The protocol is usually zero, means that the protocol is
automatically chosen according to communication type

6
socket() example

#include <sys/types.h>
#include <sys/socket.h>

int sockfd;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
// create a TCP socket

7
connect()
#include <sys/types.h>
#include <sys/socket.h>

int connect(int sockfd, const struct sockaddr *serv_addr, socklen_t addrlen);

sockfd
A descriptor identifying an unconnected socket

serv_addr
The address of the server to which the socket is to be connected
IPv4 socket uses structure sockaddr_in
IPv6 socket uses structure sockaddr_in6
 they are both based on sockaddr, need to cast them to sockaddr

addrlen
The length of the address

Return value
If no error occurs, connect() returns 0.
Otherwise, it returns -1

8
send()
#include <sys/types.h>
#include <sys/socket.h>

ssize_t send(int sockfd, const void *buf, size_t len, int flags);

sockfd
The file descriptor of the local socket from which data will be sent

buf
A buffer containing the data to be transmitted

len
The length of the data in buff

flags
Specifies the way in which the call is made
Usually 0

Return value
If no error occurs, send() returns the total number of characters sent
Otherwise, return -1

9
recv()
#include <sys/types.h>
#include <sys/socket.h>

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

sockfd
The file descriptor of the local socket where the data is receiving

buf
A buffer for the incoming data

len
The length of buf

flags
Specifies the way in which the call is made

Return value
If no error occurs, recv() returns the total number of characters received
Otherwise, return -1

10
close()
#include <unistd.h>

int close(int sockfd);

sockfd
The descriptor of the socket to be closed

Return value
If no error occurs, close() returns 0
Otherwise, return -1 (and errno will be set accordingly)

11
Excercise
• Write a TCP client, find IP of a host (by its name),
connect to a service port (ex.: 80), send a message
to the server, receive and print out the server’s
response.

12
TCP Server
• Types of server sockets
• Iterating server:
• Only one socket is opened at a time.
• Forking server:
• After an accept, a child process is forked off to
handle the connection.
• Concurrent single server:
• use select to simultaneously wait on all open
socketIds, and waking up the process only when
new data arrives

13
Iterating Server TCP Server
socket()
TCP client
bind()
socket()
listen()
connect() establish
accept()

write() data
read()

data write()

read()
end read()
close()
close()

14
bind()
#include <sys/types.h>
#include <sys/socket.h>

int bind(int sockfd, struct sockaddr *my_addr, socklen_t addrlen);

•Where
• sockfd : is the file descriptor of the socket to be bound with the address
in my_addr

• my_addr : is a pointer to the structure of the address to be assigned to


the socket sockfd

• addrlen : is the size of *my_addr


•Return value
• 0 if no errors
• -1 if has errors

15
listen()
#include <sys/socket.h>

int listen(int sockfd, int backlog);

sockfd
The file descriptor of the unconnected socket that is waiting for
connections from client

backlog
The maximum number of pending connections.

Use after bind() with a port number

Return value
0 if no errors
- if has errors

16
accept()
#include <sys/types.h>
#include <sys/socket.h>

int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);

sockfd
The file descriptor of the socket which receives the connection request to be accepted
after a listen()

addr
An optional reference pointer to the address of the client socket on the other end of the connection
The format of the addr is determined by the address family

addrlen
A optional pointer to an integer which contains the length of the address addr

Return value
Newly connected socket file descriptor if no errors
- if has errors

17
send(), recv() and close()
• Similar to TCP Client

18
Excercise
• Write a TCP server listening at port 8888, send a
message “Welcome to my first TCP server” when
never a client connect to it then wait for a message
from the client and print the received message to
the console, close the socket.

19
Excercise
• Write a TCP Server to
• Listen at port 9999 (or from command line)
• Accept a connection from a TCP Client
• Repeat
• Receive a command (in text format) from the client
• Execute the command
• Return the result to the client
• fopen(path, “rt”);
• fgets()
• send

• Use Netcat for testing


• Write your own TCP Client for testing
• Send “pwd” to know the current directory and display the
current directory as a command prompt.
20
UDP
socket()
Client
bind()
socket()
recvfrom()
bind()
Block until
Data from Data (request) sendto()
client

Process
request
Data (reply)
sendto()
recvfrom()

21
UDP
#include <sys/types.h>
#include <sys/socket.h>

ssize_t recvfrom(int s, void *buf, size_t len, int flags, struct


sockaddr *from, socklen_t *fromlen);

• s: a socket we use to receive data


• buf: a buffer uses to receive data
• len: the length of buf
• flag: how to control recvfrom function work
• from: an address structure that will tell you where the data came
from  need to use sockaddr_in or sockaddr_in6 type and cast it
• fromlen: the size of struct sockaddr.

22
UDP
• recvfrom() vs recv()
• recv() : do not need address parameter (because two
host have connected already)
• Rrecvfrom() : need address parameter – no need
connection, no reliable

23
UDP
#include <sys/types.h>
#include <sys/socket.h>

ssize_t sendto(int s, const void *buf, size_t len, int flags, const
struct sockaddr *to, socklen_t tolen);

• s: a socket we use to send data


• buf: a buffer contains data to send
• len: the length of buf
• flag: how to control sendto function work
• to: a address structure where you specify the remote socket to send
data to
• tolen: the size of struct sockaddr.

24
UDP
• A recvfrom call always receives an entire single
datagram
• Maximum datagram length is 65535 (theoretically)
but the maximum data length is 65507 (exclude
header bytes)
• Multiple recvfrom calls may receive datagrams
from multiple senders

25
MTU = 1500
UDP – IP Fragmentation What is the
maximum UDP
data size to avoid
fragmentation?

26
UDP Example
• Client send text messages
• Server response by text messages

5000

6000

27
UDP Example
• Revise client and server so that
• One server will work with 2 (or more)s clients
• Whenever the server receives a message from one
client, it sends the message to the other client

28
UDP Example
• “Client” send a file name and receive the file’s data
• “Server” response by the file content (maximum
package size is 1024)
• The first four bytes is data type:
• SIZE
• DATA
• The next 4 bytes in a SIZE package contain the
length of the file
• The next 4 bytes in a DATA package contain the
length of package’s data
• The next 4 bytes in a DATA package contain the
sequence number of the package’s data

29
UDP Broadcasting
• Broadcast address: All of bits in hostID are 1
• Local: 255.255.255.255
• Broadcasting: send data with destination
address as a broadcast address
• Only broadcast on UDP
• SocketAPI: SO_BROADCAST Socket Option

30
UDP Broadcasting

int n;
const int on = 1;
char sendline[MAXLINE], recvline[MAXLINE + 1];
socklen_t servlen;
struct sockaddr *preply_addr;
preply_addr = malloc(servlen);
setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &on,
sizeof(on));
sendto(sockfd, sendline, strlen(sendline), 0,
servaddr, servlen);

31
UDP Broadcasting

for ( ; ; ) {
len = servlen;
n = recvfrom(sockfd, recvline, MAXLINE, 0,
preply_addr, &len);
if (n < 0) {
printf("recvfrom error");
} else {
recvline[n] = 0;
printf("%s",recvline);
}
}

32
Viết chương trình chia sẻ file
• Mỗi chương trình Client khi chạy tự động
• Sinh ra tên: uname_<số ngẫu nhiên>
• Broadcast tên của mình trong mạng (“REG <Tên>”)
• Server lưu trữ danh sách client, khi nhận được lệnh “REG” thì cập
nhật danh sách tên của các client khác trong mạng
• Server nhận lệnh “LIST” thì gửi lại thông tin các client trong mạng.
“LIST N IP1 IP2 IP3 IP4”
• Client nhận lệnh “LIST” từ bàn phím thì broadcast “LIST” và lấy
thông tin Server gửi về để hiện ra màn hình.
1 NAME IP
2 NAME IP

• Client Nhận lệnh Send <File> <ID> thì
• Broadcast yêu cầu send file có thông tin về <Name>
• Đợi nhận lại phản hồi từ <Name>
• Kết nối đến <IP> và <Port> của <Name> và gửi file dùng TCP
33
Cần định nghĩa
• Định dạng gói broadcast tên
<2 Byte Length>ID_<Name>
• Định dạng gói yêu cầu gửi file
<2 Byte Length>DA_<Name>
• Định dạng gói phản hồi yêu cầu gửi file (xác nhận
là sẽ nhận)
<2 Bye Length>OK_<Name>_<TCP PORT>
• Định dạng dữ liệu file
<4 Byte Length>Nội dung file

34
Q&A

35

You might also like