Presentation is loading. Please wait.

Presentation is loading. Please wait.

Socket programming Péter Verhás August 2002

Similar presentations


Presentation on theme: "Socket programming Péter Verhás August 2002"— Presentation transcript:

1 Socket programming Péter Verhás August 2002

2 Content Socket introduction Client and Server side actions Non-blocking mode and ‘select’ Auxiliary functions Windows WSA socket handling, portable socket programming

3 Resources (where did I get all this stuff?)
Beej's Guide to Network Programming Microsoft MSDN UNIX man PAGES

4 What is a socket? It is like a file handle
You can read and write, just like a file, However the data comes from another program Therefore there are more control possibilities

5 What is it good for at all?
Communication between programs Connection oriented (TCP) and Connection less (UDP) and some more that is not detailed here.

6 How does it work with TCP?
1. Program A listens (listen) 2. Program B starts a connection (connect) 3. Program A accepts the connection (accept) 4. A and B are talking (send, recv) 5. A or B close the talk (close) Detailed on the coming 13 slides.

7 IP numbers and ports Http://192.168.14.2:80 SOURCE IP/port
DESTINATION IP/port

8 1. Listening 1a. We need a socket 1b. Bind the socket on a port
int socket(int domain, int type, int protocol); 1b. Bind the socket on a port int bind(int sockfd, struct sockaddr *my_addr, int addrlen); 1c. Listen and wait until one calls int listen(int sockfd, int backlog); 3. Accept the connection int accept(int sockfd, void *addr, int *addrlen);

9 1. Listening: phone central
1a. Request a phone equipment int socket(int domain, int type, int protocol); 1b. Connect to the outlet int bind(int sockfd, struct sockaddr *my_addr, int addrlen); 1c. Wait until rings int listen(int sockfd, int backlog); 3. Take the phone and give it to one to handle int accept(int sockfd, void *addr, int *addrlen);

10 1a. Need a socket domain AF_INET type SOCK_STREAM or SOCK_DGRAM
#include <sys/types.h> #include <sys/socket.h> int socket(int domain, int type, int protocol); domain AF_INET type SOCK_STREAM or SOCK_DGRAM protocol should be 0 for automatic choice

11 1b. Bind on a port What is this #include <sys/types.h>
struct sockaddr? #include <sys/types.h> #include <sys/socket.h> int bind(int sockfd, struct sockaddr *my_addr, int addrlen); sockfd the socket, returned by socket() my_addr the address (port) we get on addrlen the length of the structure

12 struct sockaddr struct sockaddr {
unsigned short sa_family; // address family, AF_xxx char sa_data[14];// 14 bytes address }; This is generally for all the protocols, however now we program Internet (AF_INET) and thus we need a special one: 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]; // padding What is this struct in_addr?

13 struct in_addr 4 bytes in „network byte order” Convert from long using
hostlong = INADDR_ANY; netlong = htonl(unsigned long hostlong); memcpy(in_addr_s.sin_addr, &netlong,sizeof(netlong);

14 1c. Listening int listen(int sockfd, int backlog);
Wait for incoming connection sockfd is the socket that we specified for bind call (or we are going to listen on a random port) backlog is the maximal length of the waiting queue On some systems this is limited to 20 Index.hu AdEngine 2M/day advertisement load was handled with actual size 2, sometimes 3

15 3. Accepting connection int accept(int sockfd, struct sockaddr *addr, int *addrlen); Accepts the incoming connection and returns a new socket that can be used to handle the connection. sockfd is the listening socket addr gets the IP address and port of the other side of the connection addrlen gives the size (length in bytes) of the buffer addr Return value is the new socket that will be used by the functions send/recv

16 2. Connection int connect(int sockfd, struct sockaddr *serv_addr, int addrlen); Starts a connection sockfd is the socket returned by socket() serv_addr is the address of the remote machine, struct containing IP address and port addrlen is the length of the struct Return value is zero or -1 in case of error

17 4. Sending and receiving TCP
int send(int sockfd, const void *buf, int len, unsigned int flags); int recv(int sockfd, void *buf, int len, unsigned int flags); sockfd is the socket buf is the buffer containing the bytes to send len is the length of the buffer flags is zero usually

18 4. Sending and receiving UDP
int sendto(int sockfd, const void *buf, 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); to gives where to send the package from gives where the package came tolen/fromlen the length of the structure

19 5. Closing talk Stops the socket communication how?
int shutdown(int sockfd, int how); Stops the socket communication how? 0 no more recv 1 no more send 2 no more recv nor send close(sockfd); Closes the socket and releases the resources that were allocated for socket handling

20 Programming Non-blocking Sockets
Socket Programming Programming Non-blocking Sockets

21 Blocking and non-blocking socket
All sockets are blocking by default, in other words recv/send waits fcntl(sockfd, F_SETFL, O_NONBLOCK); Sets the socket to non-blocking mode If there is nothing to read or can not write then recv/send returns -1 and errno is EWOULDBLOCK You can not wait this way for read or write because you eat up CPU!!!

22 select() synchronous I/O 3/1
int select(int numfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout); Waits until there is readable, writable socket or some error Set numfds to FD_SETSIZE readfds, writefds, exeptfds socket fields are both input and output parameters timeout millisec precision timeout value

23 select() synchronous I/O 3/2
Return value 0 in case of timeout n the number of sockets ready for transfer -1 in case of error (SOCKET_ERROR) readfds, writefds, exceptfds bits are set, every bit where send or receive can go (or error happened on non-blocking connect) is set

24 select() synchronous I/O 3/3
readfds If the socket was in listen mode then accept can go After accept, or connect recv or recvfrom can go writefds non-blocking connect was successful send or sendto can go, but may block in blocking mode if buffer space is short! exceptfds non-blocking connect failed

25 Setting and reading bit maps
FD_ZERO(fd_set *set) – cleans the bit field FD_SET(int fd, fd_set *set) – adds fd to the bit field FD_CLR(int fd, fd_set *set) – removes fd from the bit field FD_ISSET(int fd, fd_set *set) – is fd in the bit field?

26 Socket Programming Auxiliary Functions

27 getpeername() sockfd socket, after connect() or accept()
#include <sys/socket.h> int getpeername(int sockfd, struct sockaddr *addr, int *addrlen); sockfd socket, after connect() or accept() addr gives who we are talking to

28 gethostname() Gives our own host name
#include <unistd.h> int gethostname(char *hostname, size_t size); Gives our own host name hostname should point to a buffer of size size

29 gethostbyname() #include <netdb.h>
struct hostent *gethostbyname(const char *name); struct hostent { char *h_name; official name of the host char **h_aliases; NULL terminated alternate name list int h_addrtype; AF_INET int h_length; size of address char **h_addr_list; list of addresses }; #define h_addr h_addr_list[0]

30 gethostbyname() example
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <netdb.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> int main(int argc, char *argv[]) { struct hostent *h; if (argc != 2) { // error check the command line fprintf(stderr,"usage: getip address\n"); exit(1); } if ((h=gethostbyname(argv[1])) == NULL) { // get the host info herror("gethostbyname"); printf("Host name : %s\n", h->h_name); printf("IP Address : %s\n", inet_ntoa(*((struct in_addr *)h->h_addr))); return 0;

31 inet_ntoa Converts the address to string
char* inet_ntoa( struct in_addr in); Converts the address to string String returned is stored in static location

32 htonl() and htons() unsigned long htonl(unsigned long); Convert normal unsigned long (32bit) value to network order. IP address should be converted to be stored in struct in_addr: IP= hostlong=((1*256+2)*256+3)*256+4 nlong = htonl(hostlong) unsigned short htons(unsigned short); Same but for short (16bit) values, typically port numbers.

33 Socket Programming Windows Socket Architecture and UNIX socket differences Programming Sockets portable

34 UNIX vs. Windows 3/1 New type: SOCKET instead of small integer. This type is unsigned. Not a file descriptor! In case of error the return value is INVALID_SOCKET and not -1 For this reason fd_set type is different and thus Programs should stick to use the FD_XXX macros to set/read socket bitfields

35 UNIX vs. Windows 3/2 #define errno WSAGetLastError()
errno variable is NOT thread safe! close() is replaced by closesocket() A program can handle at most 64 sockets or as it is defined: #define FD_SETSIZE 1024 #include <winsock2.h>

36 UNIX vs. Windows 3/3 WSADATA wsaData;
wVersionRequested = MAKEWORD( 2, 2 ); err = WSAStartup( wVersionRequested, &wsaData ); if( err != 0 ){ fprintf(stderr,"WSA init error\n"); exit(1); } ... // let the process unload the winsock DLL WSACleanup();

37 Windows specific socket handling functions
AcceptEx accepts the connection and starts to get the data into a buffer GetAcceptExSockaddrs help fucntion for the function AcceptEx TransmitFile sends a file via the socket optimized for low level NT OS buffers (fast)

38 Thank you for your attention


Download ppt "Socket programming Péter Verhás August 2002"

Similar presentations


Ads by Google