Professional Documents
Culture Documents
01 Sockets Sockets
01 Sockets Sockets
https://en.wikipedia.org/wiki/Berkeley_sockets 3
Connection Oriented Sockets
Application 1 Application 2
Application 2 Application1
Socket Socket
Socket Socket
TCP TCP
TCP TCP
IP IP
Port Port IP IP
Host 1 Host 2 Port Port
Host 1
Ethernet
Socket
Socket Socket Socket
TCP
TCP TCP TCP
QEMU IP Port Y
IP Port Y IP Port Y
hostfwd=tcp::X-:Y IP Port
Localhost loopback Y
Host 1
IP Port X
Host 1
https://beej.us/guide/bgnet/html/single/bgnet.html 9
https://stackoverflow.com/questions/27014955/socket-connect-vs-bind 10
Socket
● domain - PF_INET or
PF_INET6
● type SOCK_STREAM
or SOCK_DGRAM
● protocol - 0 to choose
proper for given type
https://beej.us/guide/bgnet/html/single/bgnet.html 11
bind
http://man7.org/linux/man-pages/man3/getaddrinfo.3.html 18
https://beej.us/guide/bgnet/html/
Getting sockaddr - pointer to pointer
malloc’d
inside
passed by getaddrinfo,
allocated on
reference to assigned to
stack
getaddrinfo &servinfo
struct
&servinfo struct
addrinfo *
addrinfo
servinfo
https://beej.us/guide/bgnet/html/single/bgnet.html 19
https://www.tenouk.com/Module8a.html
Getting sockaddr
● Call getaddrinfo with hints, port string as
service argument, and pointer to pointer in
res
● Use res->ai_addr as sockaddr for bind()
● freeaddrinfo(res) when no longer needed
○ What if you forget to free?
■ Memory Leak
http://man7.org/linux/man-pages/man3/getaddrinfo.3.html 20
https://beej.us/guide/bgnet/html/
listen
https://stackoverflow.com/questions/27014955/socket-connect-vs-bind 21
https://pubs.opengroup.org/onlinepubs/009695399/functions/listen.html
accept
https://stackoverflow.com/questions/27014955/socket-connect-vs-bind
http://man7.org/linux/man-pages/man2/read.2.html
http://man7.org/linux/man-pages/man2/write.2.html 23
recv/send
● Use acceptedfd
(from accept()
return value) for
server application
● Use blocking or
non-blocking reads
based on flags
argument to
recv/send https://stackoverflow.com/questions/27014955/socket-connect-vs-bind
http://man7.org/linux/man-pages/man2/read.2.html
http://man7.org/linux/man-pages/man2/write.2.html 24