Docsity

WinSock Server Socket Functions - Computer Programming - Lecture Notes, Study notes of Computer Engineering and Programming

Partial preview of the text

Download WinSock Server Socket Functions - Computer Programming - Lecture Notes and more Study notes Computer Engineering and Programming in PDF only on Docsity!

  • Chapter
  • 28.1 WINS OCK S ERVER S OCKET F UNCTIONS
  • BIND
  • S OCKADDR
  • GETHOSTBYNAME
  • CONNECT
  • 28.2 S ENDING OR RECEIVING FROM SERVER
  • S END
  • RECV
  • 28.3 DIFFERENCE BETWEEN SERVER AND CLIENT SOCKET CALLS
  • 28.4 LISTEN
  • 28.5 ACCEPT
  • 28.6 WINS OCK EXAMPLE APPLICATION
  • 28.7 EXAMPLE APPLICATION
  • S UMMARY
  • EXERCISES

28.1 WinSock Server Socket Functions

Bind:

The bind function associates a local address with a socket.

int bind( SOCKET s , //socket descriptor / const struct sockaddr name , / sockaddr structure / /read the*

compatibility problem statements by the use of IPv4 and IPv6/ /connect Virtual University resource for the updated IPv informations/*

int namelen );

s: Descriptor identifying an unbound socket. name: Address to assign to the socket from the sockaddr structure. namelen: Length of the value in the name parameter, in bytes.

Return Value: If no error occurs, bind returns zero. Otherwise, it returns SOCKET_ERROR, and a specific error code can be retrieved by calling WSAGetLastError.

Error code Meaning

WSANOTINITIALISED A successful WSAStartup call must occur before using this function. WSAENETDOWN The network subsystem has failed.

WSAEACCES

Attempt to connect datagram socket to broadcast address failed because setsockopt option SO_BROADCAST is not enabled.

WSAEADDRINUSE

A process on the computer is already bound to the same fully-qualified address and the socket has not been marked to allow address reuse with SO_REUSEADDR. For example, the IP address and port are bound in the af_inet case). (See the SO_REUSEADDR socket option under setsockopt .)

WSAEADDRNOTAVAIL The specified address is not a valid address for this computer.

WSAEFAULT

The name or namelen parameter is not a valid part of the user address space, the namelen parameter is too small, the name parameter contains an incorrect address format for the associated address family, or the first two bytes of the memory block specified by

Note When using bind with the SO_EXCLUSIVEADDR or SO_REUSEADDR socket option, the socket option must be set prior to executing bind to have any affect.

Sockaddr

The sockaddr structure varies depending on the protocol selected. Except for the sa_family parameter, sockaddr contents are expressed in network byte order.

In Windows Sockets 2, the name parameter is not strictly interpreted as a pointer to a sockaddr structure. It is presented in this manner for Windows Sockets compatibility. The actual structure is interpreted differently in the context of different address families. The only requirements are that the first u_short is the address family and the total size of the memory buffer in bytes is namelen.

The structures below are used with IPv4 and IPv6, respectively. Other protocols use similar structures.

struct sockaddr_in { short sin_family; u_short sin_port; struct in_addr sin_addr; char sin_zero[8]; }; struct sockaddr_in6 { short sin6_family; u_short sin6_port; u_long sin6_flowinfo; struct in6_addr sin6_addr; u_long sin6_scope_id; }; struct sockaddr_in6_old { short sin6_family; u_short sin6_port; u_long sin6_flowinfo; struct in6_addr sin6_addr; };

Host and network byte-ordering: htonl(), htons(), ntohl(), ntohs()

gethostbyname

The gethostbyname function retrieves host information corresponding to a host name from a host database.

struct hostent FAR gethostbyname( const char** name );

name: Pointer to the null-terminated name of the host to resolve.

Return Value: If no error occurs, gethostbyname returns a pointer to the hostent structure described above. Otherwise, it returns a null pointer and a specific error number can be retrieved by calling WSAGetLastError.

Error code Meaning

WSANOTINITIALISED A successful WSAStartup call must occur before using this function. WSAENETDOWN The network subsystem has failed. WSAHOST_NOT_FOUND Authoritative answer host not found. WSATRY_AGAIN Nonauthoritative host not found, or server failure. WSANO_RECOVERY A nonrecoverable error occurred. WSANO_DATA Valid name, no data record of requested type.

WSAEINPROGRESS

A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.

WSAEFAULT The name parameter is not a valid part of the user address space.

WSAEINTR A blocking Windows Socket 1.1 call was canceled through WSACancelBlockingCall.

The gethostbyname function returns a pointer to a hostent structure—a structure allocated by Windows Sockets. The hostent structure contains the results of a successful search for the host specified in the name parameter_._

The application must never attempt to modify this structure or to free any of its components. Furthermore, only one copy of this structure is allocated per thread, so the application should copy any information it needs before issuing any other Windows Sockets function calls.

The gethostbyname function cannot resolve IP address strings passed to it. Such a request is treated exactly as if an unknown host name were passed. Use inet_addr to convert an IP address string the string to an actual IP address, then use another function, gethostbyaddr , to obtain the contents of the hostent structure.

If null is provided in the name parameter, the returned string is the same as the string returned by a successful gethostname function call.

Note The gethostbyname function does not check the size of the name parameter before passing the buffer. In improperly sized name parameters, heap corruption can occur.

The connect function is used to create a connection to the specified destination. If socket s , is unbound, unique values are assigned to the local association by the system, and the socket is marked as bound.

For connection-oriented sockets (for example, type SOCK_STREAM), an active connection is initiated to the foreign host using name (an address in the namespace of the socket.

Note: If a socket is opened, a setsockopt call is made, and then a sendto call is made, Windows Sockets performs an implicit bind function call.

When the socket call completes successfully, the socket is ready to send and receive data. If the address member of the structure specified by the name parameter is all zeroes, connect will return the error WSAEADDRNOTAVAIL. Any attempt to reconnect an active connection will fail with the error code WSAEISCONN.

For connection-oriented, nonblocking sockets, it is often not possible to complete the connection immediately. In such a case, this function returns the error WSAEWOULDBLOCK. However, the operation proceeds.

When the success or failure outcome becomes known, it may be reported in one of two ways, depending on how the client registers for notification.

¾ If the client uses the select function, success is reported in the writefds set and failure is reported in the exceptfds set. ¾ If the client uses the functions WSAAsyncSelect or WSAEventSelect , the notification is announced with FD_CONNECT and the error code associated with the FD_CONNECT indicates either success or a specific reason for failure.

For a connectionless socket (for example, type SOCK_DGRAM), the operation performed by connect is merely to establish a default destination address that can be used on subsequent send / WSASend and recv / WSARecv calls. Any datagrams received from an address other than the destination address specified will be discarded. If the address member of the structure specified by name is all zeroes, the socket will be disconnected. Then, the default remote address will be indeterminate, so send / WSASend and recv / WSARecv calls will return the error code WSAENOTCONN. However, sendto / WSASendTo and recvfrom / WSARecvFrom can still be used. The default destination can be changed by simply calling connect again, even if the socket is already connected. Any datagrams queued for receipt are discarded if name is different from the previous connect.

For connectionless sockets, name can indicate any valid address, including a broadcast address. However, to connect to a broadcast address, a socket must use setsockopt to enable the SO_BROADCAST option. Otherwise, connect will fail with the error code WSAEACCES.

When a connection between sockets is broken, the sockets should be discarded and recreated. When a problem develops on a connected socket, the application must discard and recreate the needed sockets in order to return to a stable point.

28.2 Sending or receiving from server

Send

The send function sends data on a connected socket.

int send( SOCKET s , const char* buf , int len , int flags );

s: Descriptor identifying a connected socket. buf: Buffer containing the data to be transmitted. len: Length of the data in buf , in bytes flags: Indicator specifying the way in which the call is made.

Return Values: If no error occurs, send returns the total number of bytes sent, which can be less than the number indicated by len. Otherwise, a value of SOCKET_ERROR is returned

The send function is used to write outgoing data on a connected socket. For message- oriented sockets, care must be taken not to exceed the maximum packet size of the underlying provider, which can be obtained by using getsockopt to retrieve the value of socket option SO_MAX_MSG_SIZE. If the data is too long to pass atomically through the underlying protocol, the error WSAEMSGSIZE is returned, and no data is transmitted.

The successful completion of a send does not indicate that the data was successfully delivered.

If no buffer space is available within the transport system to hold the data to be transmitted, send will block unless the socket has been placed in nonblocking mode. On nonblocking stream oriented sockets, the number of bytes written can be between 1 and the requested length, depending on buffer availability on both client and server computers. The select , WSAAsyncSelect or WSAEventSelect functions can be used to determine when it is possible to send more data.

Calling send with a zero len parameter is permissible and will be treated by implementations as successful. In such cases, send will return zero as a valid value. For message-oriented sockets, a zero-length transport datagram is sent.

remote address specified in the connection. Messages from other addresses are (silently) discarded.

For connection-oriented sockets (type SOCK_STREAM for example), calling recv will return as much information as is currently available—up to the size of the buffer specified. If the socket has been configured for in-line reception of OOB data (socket option SO_OOBINLINE) and OOB data is yet unread, only OOB data will be returned. The application can use the ioctlsocket or WSAIoctl SIOCATMARK command to determine whether any more OOB data remains to be read.

For connectionless sockets (type SOCK_DGRAM or other message-oriented sockets), data is extracted from the first enqueued datagram (message) from the destination address specified by the connect function.

If the datagram or message is larger than the buffer specified, the buffer is filled with the first part of the datagram, and recv generates the error WSAEMSGSIZE. For unreliable protocols (for example, UDP) the excess data is lost; for reliable protocols, the data is retained by the service provider until it is successfully read by calling recv with a large enough buffer.

If the socket is connection oriented and the remote side has shut down the connection gracefully, and all data has been received, a recv will complete immediately with zero bytes received. If the connection has been reset, a recv will fail with the error WSAECONNRESET.

The flags parameter can be used to influence the behavior of the function invocation beyond the options specified for the associated socket. The semantics of this function are determined by the socket options and the flags parameter. The latter is constructed by using the bitwise OR operator with any of the following values.

Value Meaning

MSG_PEEK

Peeks at the incoming data. The data is copied into the buffer but is not removed from the input queue. The function subsequently returns the amount of data that can be read in a single call to the recv (or recvfrom ) function, which may not be the same as the total amount of data queued on the socket. The amount of data that can actually be read in a single call to the recv (or recvfrom ) function is limited to the data size written in the send or sendto function call.

MSG_OOB Processes OOB data. (See DECnet Out-of-band data for a discussion of this topic.)

28.3 Difference between server and client socket calls

Figure 1 Client Connection

Socket()

Connect()

Send/recv()

closesocket

Socket()

bind()

Listen()

accept

Recv/send

closesocket

28.5 Accept

The accept function permits an incoming connection attempt on a socket.

SOCKET accept( SOCKET s , /socket descriptor/ struct sockaddr*** addr , /sockaddr structure/ int*** addrlen /string length returned/ );

s: Descriptor identifying a socket that has been placed in a listening state with the listen function. The connection is actually made with the socket that is returned by accept.

addr: Optional pointer to a buffer that receives the address of the connecting entity, as known to the communications layer. The exact format of the addr parameter is determined by the address family that was established when the socket from the sockaddr structure was created.

Addrlen: Optional pointer to an integer that contains the length of addr.

Return Values: If no error occurs, accept returns a value of type SOCKET that is a descriptor for the new socket. This returned value is a handle for the socket on which the actual connection is made. Otherwise, a value of INVALID_SOCKET is returned

The accept function extracts the first connection on the queue of pending connections on socket s. It then creates and returns a handle to the new socket. The newly created socket is the socket that will handle the actual connection; it has the same properties as socket s , including the asynchronous events registered with the WSAAsyncSelect or WSAEventSelect functions.

The accept function can block the caller until a connection is present if no pending connections are present on the queue, and the socket is marked as blocking. If the socket is marked as nonblocking and no pending connections are present on the queue, accept returns an error as described in the following. After the successful completion of accept returns a new socket handle, the accepted socket cannot be used to accept more connections. The original socket remains open and listens for new connection requests.

The parameter addr is a result parameter that is filled in with the address of the connecting entity, as known to the communications layer. The exact format of the addr parameter is determined by the address family in which the communication is occurring. The addrlen is a value-result parameter; it should initially contain the amount of space pointed to by addr ; on return it will contain the actual length (in bytes) of the address returned.

The accept function is used with connection-oriented socket types such as SOCK_STREAM. If addr and/or addrlen are equal to NULL, then no information about the remote address of the accepted socket is returned.

28.6 WinSock Example Application

A client showing simple communication to either our own small server, or some server on the internet, e.g. WHOIS servers, HTTP server, time service etc. A small utility that synchronizes system time with a source on the internet, accounting for transmission-delays

Screen shot of our application.

28.7 Example Application

Int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { WSADATA wsaData; HOSTENT *ptrHostEnt; struct sockaddr_in serverSockAddr; // the address of the socket to connect to

int abc;

// try initialising the windows sockets library if(WSAStartup( MAKEWORD(1,1), &wsaData)) // request WinSock ver 1. { MessageBox(NULL, "Error initialising sockets library.", "WinSock Error", MB_OK | MB_ICONSTOP); return 1; }

_/Get host name /_

BOOL CALLBACK mainDialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { int wID, wNotificationCode; char domainName[MAX_DOMAIN_LEN+2+1]; // accomodate CR/LF/NULL char result[BUFFER_SIZE], *startOfBuffer = result; int bytesReceived;

switch(message) { case WM_INITDIALOG: SendDlgItemMessage(hDlg, IDC_EDIT_DOMAIN, EM_LIMITTEXT, MAX_DOMAIN_LEN, 0); return TRUE; break;

case WM_COMMAND: wNotificationCode = HIWORD(wParam); wID = LOWORD(wParam); switch(wID) { case IDC_BUTTON_SEND: EnableWindow(GetDlgItem(hDlg, IDC_BUTTON_SEND), FALSE); // disable for 2nd use GetDlgItemText(hDlg, IDC_EDIT_DOMAIN, (LPSTR)domainName, MAX_DOMAIN_LEN+1); strcpy(domainName+strlen(domainName), "\r\n"); if(send(clientSocket, (const char *)domainName, strlen(domainName), 0) == SOCKET_ERROR) EndDialog(hDlg, 1); else {

bytesReceived = recv(clientSocket, startOfBuffer, BUFFER_SIZE-1, 0); // -1 for NULL while(bytesReceived > 0)// 0:close //SOCKET_ERROR:error { startOfBuffer += bytesReceived; // //move it forward bytesReceived = recv(clientSocket, startOfBuffer, BUFFER_SIZE-(startOfBuffer-result)-1, 0); // -1 for NULL }

if(startOfBuffer != result) // something received *startOfBuffer = NULL; // NULL terminate else strcpy(result, "Null Response");

SetDlgItemText(hDlg, IDC_EDIT_RESULT, result); }

break;

case IDCANCEL: EndDialog(hDlg, 0); break; } return TRUE; break;

default: return FALSE; } return TRUE; }

Summary

In this lecture, we studied about WinSock functions. These functions include connect, recv, send, accept, bind, gethotbyname, etc. we saw the difference between client socket connection and server socket connection. And finally we made application that is whoisserver. This application tells that the name is registered name or not. If the name is registered, then we cannot register it again.

Note: These lectures explain only IPv4, this protocol is being replaced by IPv6. New resource should use IPv6. For New Internet Protocol version and programming using IPv6, connect to Virtual University resource online.

Exercises

  1. Create a simple socket client server application that uses stream socket and TCP/IP protocols. On connecting, the client server must show message that client has been connected.