









Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!










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.
Attempt to connect datagram socket to broadcast address failed because setsockopt option SO_BROADCAST is not enabled.
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.
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
name does not match the address family associated with the socket descriptor s.
A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function. WSAEINVAL The socket is already bound to an address. WSAENOBUFS Not enough buffers available, too many connections. WSAENOTSOCK The descriptor is not a socket.
The bind function is used on an unconnected socket before subsequent calls to connect or listen functions. It is used to bind to either connection-oriented (stream) or connectionless (datagram) sockets. When a socket is created with a call to the socket function, it exists in a namespace (address family), but it has no name assigned to it. Use the bind function to establish the local association of the socket by assigning a local name to an unnamed socket.
A name consists of three parts when using the Internet address family:
In Windows Sockets 2, the name parameter is not strictly interpreted as a pointer to a sockaddr structure. It is cast this way for Windows Sockets 1.1 compatibility. Service providers are free to regard it as a pointer to a block of memory of size namelen. The first 2 bytes in this block (corresponding to the sa_family member of the sockaddr structure) must contain the address family that was used to create the socket. Otherwise, an error WSAEFAULT occurs.
If an application does not care what local address is assigned, specify the manifest constant value ADDR_ANY for the sa_data member of the name parameter. This allows the underlying service provider to use any appropriate network address, potentially simplifying application programming in the presence of multihomed hosts (that is, hosts that have more than one network interface and address).
For TCP/IP, if the port is specified as zero, the service provider assigns a unique port to the application with a value between 1024 and 5000. The application can use getsockname after calling bind to learn the address and the port that has been assigned to it. If the Internet address is equal to INADDR_ANY, getsockname cannot necessarily supply the address until the socket is connected, since several addresses can be valid if the host is multihomed. Binding to a specific port number other than port 0 is discouraged for client applications, since there is a danger of conflicting with another socket already using that port number.
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.
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 establishes a connection to a specified socket.
int connect( SOCKET s , const struct sockaddr* name , int namelen );
s: Descriptor identifying an unconnected socket.
name: Name of the socket in the sockaddr structure to which the connection should be established.
namelen: Length of name , in bytes
Return Values: If no error occurs, connect returns zero. Otherwise, it returns SOCKET_ERROR, and a specific error code can be retrieved by calling WSAGetLastError.
On a blocking socket, the return value indicates success or failure of the connection attempt.
With a nonblocking socket, the connection attempt cannot be completed immediately. In this case, connect will return SOCKET_ERROR, and WSAGetLastError will return WSAEWOULDBLOCK. In this case, there are three possible scenarios:
¾ Use the select function to determine the completion of the connection request by checking to see if the socket is writeable. ¾ If the application is using WSAAsyncSelect to indicate interest in connection events, then the application will receive an FD_CONNECT notification indicating that the connect operation is complete (successfully or not). ¾ If the application is using WSAEventSelect to indicate interest in connection events, then the associated event object will be signaled indicating that the connect operation is complete (successfully or not).
Until the connection attempt completes on a nonblocking socket, all subsequent calls to connect on the same socket will fail with the error code WSAEALREADY, and WSAEISCONN when the connection completes successfully. Due to ambiguities in version 1.1 of the Windows Sockets specification, error codes returned from connect while a connection is already pending may vary among implementations. As a result, it is not recommended that applications use multiple calls to connect to detect connection completion. If they do, they must be prepared to handle WSAEINVAL and WSAEWOULDBLOCK error values the same way that they handle WSAEALREADY, to assure robust execution.
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.
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.
The flags parameter can be used to influence the behavior of the function 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_DONTROUTE Specifies that the data should not be subject to routing. A Windows Sockets service provider can choose to ignore this flag.
Sends OOB data (stream-style socket such as SOCK_STREAM only. Also see DECnet Out-Of-band data for a discussion of this topic).
The recv function receives data from a connected or bound socket.
int recv( SOCKET s , char* buf , int len , int flags );
s: Descriptor identifying a connected socket. buf: Buffer for the incoming data. len: Length of buf , in bytes flags: Flag specifying the way in which the call is made.
Return Values: If no error occurs, recv returns the number of bytes received. If the connection has been gracefully closed, the return value is zero. Otherwise, a value of SOCKET_ERROR is returned,
The recv function is used to read incoming data on connection-oriented sockets, or connectionless sockets. When using a connection-oriented protocol, the sockets must be connected before calling recv. When using a connectionless protocol, the sockets must be bound before calling recv.
The local address of the socket must be known. For server applications, use an explicit bind function or an implicit accept or WSAAccept function. Explicit binding is discouraged for client applications. For client applications, the socket can become bound implicitly to a local address using connect , WSAConnect , sendto , WSASendTo , or WSAJoinLeaf.
For connected or connectionless sockets, the recv function restricts the addresses from which received messages are accepted. The function only returns messages from the
Figure 1 Client Connection
Socket()
Connect()
Send/recv()
closesocket
Socket()
bind()
Listen()
accept
Recv/send
closesocket
Figure 2 Server Connection
The listen function places a socket in a state in which it is listening for an incoming connection.
int listen( SOCKET s , int backlog );
s: Descriptor identifying a bound, unconnected socket.
Backlog: Maximum length of the queue of pending connections. If set to SOMAXCONN, the underlying service provider responsible for socket s will set the backlog to a maximum reasonable value. There is no standard provision to obtain the actual backlog value.
Return Values: If no error occurs, listen returns zero. Otherwise, a value of SOCKET_ERROR is returned.
To accept connections, a socket is first created with the socket function and bound to a local address with the bind function, a backlog for incoming connections is specified with listen, and then the connections are accepted with the accept function. Sockets that are connection oriented those of type SOCK_STREAM for example, are used with listen. The socket s is put into passive mode where incoming connection requests are acknowledged and queued pending acceptance by the process.
The listen function is typically used by servers that can have more than one connection request at a time. If a connection request arrives and the queue is full, the client will receive an error with an indication of WSAECONNREFUSED.
If there are no available socket descriptors, listen attempts to continue to function. If descriptors become available, a later call to listen or accept will refill the queue to the current or most recent backlog, if possible, and resume listening for incoming connections.
An application can call listen more than once on the same socket. This has the effect of updating the current backlog for the listening socket. Should there be more pending connections than the new backlog value, the excess pending connections will be reset and dropped.
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.
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 /_
if(!(ptrHostEnt = gethostbyname(WHOIS_SERVER_NAME))) { MessageBox(NULL, "Could not resolve WHOIS server name.", "WinSock Error", MB_OK | MB_ICONSTOP); WSACleanup(); return 1; }
serverSockAddr.sin_family = AF_INET; // fill the address structure with appropriate values serverSockAddr.sin_port = htons(WHOIS_PORT); // MUST convert to network byte-order memset(serverSockAddr.sin_zero, 0, sizeof(serverSockAddr.sin_zero)); memcpy(&serverSockAddr.sin_addr.S_un.S_addr, ptrHostEnt->h_addr_list[0], sizeof(unsigned long));
clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(clientSocket == INVALID_SOCKET) { MessageBox(NULL, "Error creating client socket.", "WinSock Error", MB_OK | MB_ICONSTOP); WSACleanup(); return 1; }
_/Start Connection/_**
if(connect(clientSocket, (struct sockaddr *)&serverSockAddr, sizeof(serverSockAddr))) {
abc = WSAGetLastError();
MessageBox(NULL, "Error connecting to WHOIS server.", "WinSock Error", MB_OK | MB_ICONSTOP); WSACleanup(); return 1; }
if(DialogBox(hInstance, MAKEINTRESOURCE(IDD_DIALOG_MAIN), NULL, mainDialogProc) == 1) MessageBox(NULL, "Error occurred while sending data to WHOIS server.", "WinSock Error", MB_OK | MB_ICONSTOP);
WSACleanup();
return 0;
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; }
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.