Top 26 Socket Programming Interview Questions You Must Prepare 19.Mar.2024

Specifying a Remote Socket - connect()

#include <ltsys/types.h>
#include <ltsys/socket.h>
int connect(int s, struct sockaddr *name, int namelen)


The bind() call only allows specification of a local address. To specify the remote side of an address connection the connect() call is used. In the call to connect, s is the file descriptor for the socket. name is a pointer to a structure of type sockaddr:

struct sockaddr {
u_short sa_family;
char sa_data[14];
};
As with the bind() system call, name.sa_family should be AF_UNIX. name.sa_data should contain up to 14 bytes of a file name which will be assigned to the socket. namelen gives the actual length of name. A return value of 0 indicates success, while a value of -1 indicates failure with errno describing the error.

A sample code fragment:
struct sockaddr name;
name.sa_family = AF_UNIX;
strcpy(name.sa_data, "/tmp/sock");
if (connect(s, &name, strlen
(name.sa_data) +
sizeof(name.sa_family)) < 0) 
{
printf("connect failure %dn", errno);
}

Socket Creation Using socket()
#include <ltsys/types.h>
#include <ltsys/socket.h>
int socket(int af, int type, int protocol)

socket() is very similar to socketpair() except that only one socket is created instead of two. This is most commonly used if the process you wish to communicate with is not a child process. The af, type, and protocol fields are used just as in the socketpair() system call.

On success, a file descriptor to the socket is returned. On failure, -1 is returned and errno describes the problem.

The combination of an IP address and a port number is called a socket.

#include <ltsys/types.h>
#include <ltsys/socket.h>
int accept(int sockfd, struct sockaddr *name,int *namelen)

The accept() call establishes a client-server connection on the server side. (The client requests the connection using the connect() system call.) The server must have created the socket using socket(), given the socket a name using bind(), and established a listen queue using listen().

sockfd is the socket file descriptor returned from the socket() system call. name is a pointer to a structure of type sockaddr as described above

struct sockaddr {
u_short sa_family;
char sa_data[14];
};

Upon successful return from accept(), this structure will contain the protocol address of the client's socket. The data area pointed to by namelen should be initialized to the actual length of name. Upon successful return from accept, the data area pointed to by namelen will contain the actual length of the protocol address of the client's socket.

If successful, accept() creates a new socket of the same family, type, and protocol as sockfd. The file descriptor for this new socket is the return value of accept(). This new socket is used for all communications with the client.

If there is no client connection request waiting, accept() will block until a client request is queued.

accept() will fail mainly if sockfd is not a file descriptor for a socket or if the socket type is not SOCK_STREAM. In this case, accept() returns the value -1 and errno describes the problem.

Sockets can be used to write client-server applications using a connection-oriented client-server technique. Some characteristics of this technique include:

  • The server can handle multiple client requests for connection and service.
  • The server responds to any one client's request independently of all other clients.
  • A client knows how to establish a connection with the server.

The client-server connection, when established, remains in existence until either the client or the server explicitly breaks it, much like a trouble-free telephone call. The socket used for this connection is called a connection-oriented socket.

The socket type is specified as SOCK_STREAM. As a result, the process receiving a message processes that message by the following rules:

  • The data transmitted has no boundaries.
  • All bytes in a received message must be read before the next message can be processed.
  • Bytes in a received message can be read in a loop program control structure since no data bytes are discarded.
  • The server will usually fork() a child process upon establishment of a client connection.
  • This child server process is designed to communicate with exactly one client process.
  • The child server process performs the requested service for its connected client.
  • The child server process terminates when the service request has been completed.

Functions listen() and accept() enable the server to listen for service requests. read() and write() may be used by client and server to send/receive messages; send() and recv() may also be used.

  • TCP and UDP are both transport-level protocols. TCP is designed to provide reliable communication across a variety of reliable and unreliable networks and internets.
  • UDP provides a connectionless service for application-level procedures. Thus, UDP is basically an unreliable service; delivery and duplicate protection are not guareented.

If you are programming a client, then you would open a socket like this:

Socket MyClient;

MyClient = new Socket("Machine name", PortNumber);

Where Machine name is the machine you are trying to open a connection to, and PortNumber is the port (a number) on which the server you are trying to connect to is running. When selecting a port number, you should note that port numbers between 0 and 1,023 are reserved for privileged users (that is, super user or root). These port numbers are reserved for standard services, such as email, FTP, and HTTP. When selecting a port number for your server, select one that is greater than 1,023!

In the example above, we didn't make use of exception handling, however, it is a good idea to handle exceptions. (From now on, all our code will handle exceptions!) The above can be written as:

Socket MyClient;
try {
MyClient = new Socket("Machine name", PortNumber);
}
catch (IOException e) {
System.out.println(e);
}
If you are programming a server, then this is how you open a socket:

ServerSocket MyService;
try {
MyServerice = new ServerSocket(PortNumber);
}
catch (IOException e) {
System.out.println(e);
}

When implementing a server you also need to create a socket object from the ServerSocket in order to listen for and accept connections from clients.

Socket clientSocket = null;
try {
serviceSocket = MyService.accept();
}
catch (IOException e) {
System.out.println(e);
}

Giving a Socket a Name - bind()

#include <ltsys/types.h>
#include <ltsys/socket.h>
int bind(int s, struct sockaddr *name, int namelen)

Recall that, using socketpair(), sockets could only be shared between parent and child processes or children of the same parent. With a name attached to the socket, any process on the system can describe (and use) it.

In a call to bind(), s is the file descriptor for the socket, obtained from the call to socket(). name is a pointer to a structure of type sockaddr. If the address family is AF_UNIX (as specified when the socket is created), the structure is defined as follows:

struct sockaddr {
u_short sa_family;
char sa_data[14];
};

name.sa_family should be AF_UNIX. name.sa_data should contain up to 14 bytes of a file name which will be assigned to the socket. namelen gives the actual length of name, that is, the length of the initialized contents of the data structure.

A value of 0 is return on success. On failure, -1 is returned with errno describing the error.

Example:

struct sockaddr name;
int s;
name.sa_family = AF_UNIX;
strcpy(name.sa_data, "/tmp/sock");
if((s = socket(AF_UNIX, SOCK_STREAM, 0) < 0)
{
printf("socket create failure %dn", errno);
exit(0);
}
if (bind(s, &name, strlen(name.sa_data) +
sizeof(name.sa_family)) < 0)
printf("bind failure %dn", errno);

 

/*
Code Sample: Make a Socket a Listen-only
Connection Endpoint - listen()
by GlobalGuideline.com*/
#include <ltsys/types.h>
#include <ltsys/socket.h>
int listen(int s, int backlog)
/*
listen establishes the socket as a passive
endpoint of a connection. It does not suspend process execution.
*/
/* 
No messages can be sent through this socket.
Incoming messages can be received.
*/
/*
s is the file descriptor associated with the socket created using the socket() system call. backlog is the size of the queue of waiting requests while the server is busy with a service request. The current system-imposed maximum value is 5.

*/
/*
0 is returned on success, -1 on error with errno indicating the problem.

*/
Example:
#include <ltsys/types.h>
#include <ltsys/socket.h>
int sockfd; /* socket file descriptor */
if(listen(sockfd, 5) < 0)
printf ("listen error %dn", errno);

Sending to a Named Socket - sendto()

int sendto(int s, char *msg, int len, int flags, struct sockaddr *to, int tolen)

This function allows a message msg of length len to be sent on a socket with descriptor s to the socket named by to and tolen, where tolen is the actual length of to. flags will always be zero for our purposes. The number of characters sent is the return value of the function. On error, -1 is returned and errno describes the error.

An example:

struct sockaddr to_name;
to_name.sa_family = AF_UNIX;
strcpy(to_name.sa_data, "/tmp/sock");
if (sendto(s, buf, sizeof(buf),
0, &to_name,
strlen(to_name.sa_data) +
sizeof(to_name.sa_family)) < 0) {
printf("send failuren");
exit(1);
}

Receiving on a Named Socket - recvfrom()
#include <ltsys/types.h>
#include <ltsys/socket.h>
int recvfrom(int s, char *msg, int len, int flags,struct sockaddr *from, int *fromlen)
This function allows a message msg of maximum length len to be read from a socket with descriptor s from the socket named by from and fromlen, where fromlen is the actual length of from. The number of characters actually read from the socket is the return value of the function. On error, -1 is returned and errno describes the error. flags may be 0, or may specify MSG_PEEK to examine a message without actually receiving it from the queue.

If no message is available to be read, the process will suspend waiting for one unless the socket is set to nonblocking mode (via an ioctl call).

The system I/O call read() can also be used to read data from a socket.

You should always close the output and input stream before you close the socket:

On the client side:
try {
output.close();
input.close();
MyClient.close();
}
catch (IOException e) {
System.out.println(e);
}


On the server side:
try {
output.close();
input.close();
serviceSocket.close();
MyService.close();
}
catch (IOException e) {
System.out.println(e);
}

It occurs when two or more processes are reading or writing some shared data and the final result depends on who runs precisely when.

Code Sample: How to disposing of a Socket :

#include <ltstdio.h>
void close(int s).
/* The I/O call close() will close the socket descriptor s just as it closes any open file descriptor.

Example - sendto() and recvfrom()
*/
/* receiver */
#include <ltsys/types.h>
#include <ltsys/socket.h>
struct sockaddr myname;
struct sockaddr from_name;
char buf[80];
main()
{
int sock;
int fromlen, cnt;
sock = socket(AF_UNIX, SOCK_DGRAM, 0);
if (sock < 0) {
printf("socket failure %dn", errno);
exit(1);
}
myname.sa_family = AF_UNIX;
strcpy(myname.sa_data, "/tmp/tsck");
if (bind(sock, &myname,
strlen(myname.sa_data) +
sizeof(name.sa_family)) < 0) {
printf("bind failure %dn", errno);
exit(1);
}
cnt = recvfrom(sock, buf, sizeof(buf),
0, &from_name, &fromlen);
if (cnt < 0) {
printf("recvfrom failure %dn", errno);

exit(1);

}

buf[cnt] = ''; /* assure null byte */
from_name.sa_data[fromlen] = '';
printf("'%s' received from %sn",
buf, from_name.sa_data);
}

/* sender */
#include <ltsys/types.h>
#include <ltsys/socket.h>
char buf[80];
struct sockaddr to_name;
main()
{
int sock;
sock = socket(AF_UNIX, SOCK_DGRAM, 0);
if (sock < 0) {
printf("socket failure %dn", errno);
exit(1);

}
to_name.sa_family = AF_UNIX;
strcpy(to_name.sa_data, "/tmp/tsck");
strcpy(buf, "test data line");
cnt = sendto(sock, buf, strlen(buf),
0, &to_name,
strlen(to_name.sa_data) + sizeof(to_name.sa_family));
if (cnt < 0) {
printf("sendto failure %dn", errno);
exit(1);
}
}

Two additional data transfer library calls, namely send() and recv(), are available if the sockets are connected. They correspond very closely to the read() and write() functions used for I/O on ordinary file descriptors.

#include <ltsys/types.h>
#include <ltsys/socket.h>
int send(int sd, char *buf, int len, int flags)
int recv(int sd, char * buf, int len, int flags)

In both cases, sd is the socket descriptor. For send(), buf points to a buffer containing the data to be sent, len is the length of the data and flags will usually be @The return value is the number of bytes sent if successful. If not successful, -1 is returned and errno describes the error.

For recv(), buf points to a data area into which the received data is copied, len is the size of this data area in bytes, and flags is usually either 0 or set to MSG_PEEK if the received data is to be retained in the system after it is received. The return value is the number of bytes received if successful. If not successful, -1 is returned and errno describes the error. 

On the client side, you can use the DataInputStream class to create an input stream to receive response from the server:

DataInputStream input;
try {
input = new DataInputStream(MyClient.getInputStream());
}
catch (IOException e) {
System.out.println(e);
}
The class DataInputStream allows you to read lines of text and Java primitive data types in a portable way. It has methods such as read, readChar, readInt, readDouble, and readLine,. Use whichever function you think suits your needs depending on the type of data that you receive from the server.

On the server side, you can use DataInputStream to receive input from the client:

DataInputStream input;
try {
input = new DataInputStream(serviceSocket.getInputStream());
}
catch (IOException e) {
System.out.println(e);
}

On the client side, you can create an output stream to send information to the server socket using the class PrintStream or DataOutputStream of java.io:

PrintStream output;
try {
output = new PrintStream(MyClient.getOutputStream());
}
catch (IOException e) {
System.out.println(e);
}

The class PrintStream has methods for displaying textual representation of Java primitive data types. Its Write and println methods are important here. Also, you may want to use the DataOutputStream:

DataOutputStream output;
try {
output = new DataOutputStream(MyClient.getOutputStream());
}
catch (IOException e) {
System.out.println(e);
}

The class DataOutputStream allows you to write Java primitive data types; many of its methods write a single Java primitive type to the output stream. The method writeBytes is a useful one.

On the server side, you can use the class PrintStream to send information to the client.

PrintStream output;
try {
output = new PrintStream(serviceSocket.getOutputStream());
}
catch (IOException e) {
System.out.println(e);
}

Note: You can use the class DataOutputStream as mentioned above.

Hiding data within the class and making it available only through the methods. This technique is used to protect your class against accidental changes to fields, which might leave the class in an inconsistent state.

  1. Physical,
  2. Data Link,
  3. Network,
  4. Transport,
  5. Session,
  6. Presentation and
  7. Application Layers.

JavaBeans are reusable software components written in the Java programming language, designed to be manipulated visually by a software develpoment environment, like JBuilder or VisualAge for Java. They are similar to Microsoft’s ActiveX components, but designed to be platform-neutral, running anywhere there is a Java Virtual Machine (JVM).

Multiprogramming is a rapid switching of the CPU back and forth between processes.

Sockets are a generalized networking capability first introduced in 4.1cBSD and subsequently refined into their current form with 4.2BSD. The sockets feature is available with most current UNIX system releases. (Transport Layer Interface (TLI) is the System V alternative). Sockets allow communication between two different processes on the same or different machines. Internet protocols are used by default for communication between machines; other protocols such as DECnet can be used if they are available.

To a programmer a socket looks and behaves much like a low level file descriptor. This is because commands such as read() and write() work with sockets in the same way they do with files and pipes. The differences between sockets and normal file descriptors occurs in the creation of a socket and through a variety of special operations to control a socket. These operations are different between sockets and normal file descriptors because of the additional complexity in establishing network connections when compared with normal disk access.

For most operations using sockets, the roles of client and server must be assigned. A server is a process which does some function on request from a client. As will be seen in this discussion, the roles are not symmetric and cannot be reversed without some effort.

This description of the use of sockets progresses in three stages:

  1. The use of sockets in a connectionless or datagram mode between client and server processes on the same host. In this situation, the client does not explicitly establish a connection with the server. The client, of course, must know the server's address. The server, in turn, simply waits for a message to show up. The client's address is one of the parameters of the message receive request and is used by the server for response.
  2. The use of sockets in a connected mode between client and server on the same host. In this case, the roles of client and server are further reinforced by the way in which the socket is established and used. This model is often referred to as a connection-oriented client-server model.
  3. The use of sockets in a connected mode between client and server on different hosts. This is the network extension of Stage 2, above.

The connectionless or datagram mode between client and server on different hosts is not explicitly discussed here. Its use can be inferred from the presentations made in Stages 1 and 3.

A NULL pointer is a pointer of any type whose value is zero. A void pointer is a pointer to an object of an unknown type, and is guaranteed to have enough bits to hold a pointer to any object. A void pointer is not guaranteed to have enough bits to point to a function (though in general practice it does).

A socket is one end-point of a two-way communication link between two programs running on the network. Socket classes are used to represent the connection between a client program and a server program. The java.net package provides two classes--Socket and ServerSocket--that implement the client side of the connection and the server side of the connection, respectively.

Advantages of Java Sockets:

  • Sockets are flexible and sufficient. Efficient socket based programming can be easily implemented for general communications.
  • Sockets cause low network traffic. Unlike HTML forms and CGI scripts that generate and transfer whole web pages for each new request, Java applets can send only necessary updated information.

Disadvantages of Java Sockets:

  • Security restrictions are sometimes overbearing because a Java applet running in a Web browser is only able to establish connections to the machine where it came from, and to nowhere else on the network
  • Despite all of the useful and helpful Java features, Socket based communications allows only to send packets of raw data between applications. Both the client-side and server-side have to provide mechanisms to make the data useful in any way.
  • Since the data formats and protocols remain application specific, the re-use of socket based implementations is limited.

  • Physical Layer - covers the physical interface between devices and the rules by which bits are passed from one to another.
  • Data Link Layer - attempts o make the physical link reliable and provides the means to activate, maintain, and deactivate the link.
  • Network Layer - provides for the transfer of information between end systems across some sort communications network.
    • Transport Layer - provides a mechanism for the exchange of data between end system.
    • Session Layer - provides the mechanism for controlling the dialogue between applications in end systems.
    • Presentation Layer - defines the format of the data to be exchanged between applications and offers application programs a set of data transformation services.
    • Application Layer - provides a means for application programs to access the OSI environment.