Socket Programming Interview Preparation Guide
Download PDF

Socket Programming Interview Questions and Answers will guide us now that in computing, network programming, essentially identical to socket programming or client-server programming, involves writing computer programs that communicate with other programs across a computer network. The program or process initiating the communication is called a client process, and the program waiting for the communication to be initiated is the server process. Learn Socket Programming with this Interview guide

62 Socket Programming Questions and Answers:

Table of Contents

Socket Programming Interview Questions and Answers
Socket Programming Interview Questions and Answers

1 :: What Is Socket?

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.

2 :: How does the race condition occur?

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

3 :: What is multiprogramming?

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

4 :: Name the seven layers of the OSI Model and describe them briefly?

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.

5 :: What is the difference between TCP and UDP?

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.

6 :: What does a socket consists of?

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

7 :: What is a JavaBean?

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).

8 :: What are the seven layers(OSI model) of networking?

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

9 :: What are some advantages and disadvantages of Java Sockets?

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.

10 :: What is the difference between a NULL pointer and a void pointer?

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).

11 :: What is encapsulation technique?

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.

12 :: Socket Programming Interview Questions

1. User(s) are complaining of delays when using the network. What would you do?
2. What are some of the problems associated with operating a switched LAN?
3. Name some of the ways of combining TCP/IP traffic and SNA traffic over the same link.
4. What sort of cabling is suitable for Fast Ethernet protocols?
5. What is a Class D IP address?
6. Why do I sometimes lose a server's address when using more than one server?
7. What is Firewall?
8. How do I monitor the activity of sockets?
9. How would I put my socket in non-blocking mode?
10. What are RAW sockets?
11. What is the role of TCP protocol and IP protocol.
12. What is UDP?
13. How can I make my server a daemon?
14. How should I choose a port number for my server?
15. Layers in TCP/IP
16. How can I be sure that a UDP message is received?
17. How to get IP header of a UDP message
18. Writing UDP/SOCK_DGRAM applications
19. How many bytes in an IPX network address?
20. What is the difference between MUTEX and Semaphore?
21. What is priority inversion?
22. Different Solutions to dining philosophers problem.
23. What is a message queue?
24. Questions on Shared Memory.
25. What is DHCP?
26. Working of ping, telnet, gopher.
27. Can I connect two computers to internet using same line ?
28. Working of TCP and SSL Handshake
29. How P2P softwares work?
30. Setting up TOMCAT web service
31. Port numbers for FTP, HTTP, telnet, POP, finger
32. Difference - Passive FTP, Active FTP
33. Maximum Transmission Unit (MTU) what is it?
34. Security threats due to use of CGI
35. What is "spoofing"
36. Where could you find Apache server web log
37. Find web visitors by country
38. What is Virtual Private Network (VPN) and how does it work?
39. How does routing work?

13 :: How do I open a socket?

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);
}

14 :: How do I create an input stream?

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);
}

15 :: How do I create an output stream?

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.

16 :: How do I close sockets?

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);
}

17 :: Explain simple mail transfer protocol?

Write an SMTP (simple mail transfer protocol) client -- one so simple that we have all the data encapsulated within the program. You may change the code around to suit your needs. An interesting modification would be to change it so that you accept the data from the command-line argument and also get the input (the body of the message) from standard input. Try to modify it so that it behaves the same as the mail program that comes with Unix.

import java.io.*;
import java.net.*;
public class smtpClient {
public static void main(String[] args) {
// declaration section:
// smtpClient: our client socket
// os: output stream
// is: input stream
Socket smtpSocket = null;
DataOutputStream os = null;
DataInputStream is = null;
// Initialization section:
// Try to open a socket on port 25
// Try to open input and output streams
try {
smtpSocket = new Socket("hostname", 25);
os = new DataOutputStream(smtpSocket.getOutputStream());
is = new DataInputStream(smtpSocket.getInputStream());
} catch (UnknownHostException e) {
System.err.println("Don't know about host: hostname");
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: hostname");
}
// If everything has been initialized then we want to write some data
// to the socket we have opened a connection to on port 25
if (smtpSocket != null && os != null && is != null) {
try {
// The capital string before each colon has a special meaning to SMTP
// you may want to read the SMTP specification, RFC1822/3
os.writeBytes("HELOn");
os.writeBytes("MAIL From: k3is@fundy.csd.unbsj.can");
os.writeBytes("RCPT To: k3is@fundy.csd.unbsj.can");
os.writeBytes("DATAn");
os.writeBytes("From: k3is@fundy.csd.unbsj.can");
os.writeBytes("Subject: testingn");
os.writeBytes("Hi theren"); // message body
os.writeBytes("n.n");
os.writeBytes("QUIT");
// keep on reading from/to the socket till we receive the "Ok" from SMTP,
// once we received that then we want to break.
String responseLine;
while ((responseLine = is.readLine()) != null) {
System.out.println("Server: " + responseLine);
if (responseLine.indexOf("Ok") != -1) {
break;
}
}
// clean up:
// close the output stream
// close the input stream
// close the socket
os.close();
is.close();
smtpSocket.close();
} catch (UnknownHostException e) {
System.err.println("Trying to connect to unknown host: " + e);
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
}
}

When programming a client, you must follow these four steps:

* Open a socket.
* Open an input and output stream to the socket.
* Read from and write to the socket according to the server's protocol.
* Clean up.

These steps are pretty much the same for all clients. The only step that varies is step three, since it depends on the server you are talking to.

18 :: Explain simple Echo server?

2. Echo server


Write a server. This server is very similar to the echo server running on port 7. Basically, the echo server receives text from the client and then sends that exact text back to the client. This is just about the simplest server you can write. Note that this server handles only one client. Try to modify it to handle multiple clients using threads.

import java.io.*;
import java.net.*;
public class echo3 {
public static void main(String args[]) {
// declaration section:
// declare a server socket and a client socket for the server
// declare an input and an output stream
ServerSocket echoServer = null;
String line;
DataInputStream is;
PrintStream os;
Socket clientSocket = null;
// Try to open a server socket on port 9999
// Note that we can't choose a port less than 1023 if we are not
// privileged users (root)
try {
echoServer = new ServerSocket(9999);
}
catch (IOException e) {
System.out.println(e);
}
// Create a socket object from the ServerSocket to listen and accept
// connections.
// Open input and output streams
try {
clientSocket = echoServer.accept();
is = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());
// As long as we receive data, echo that data back to the client.
while (true) {
line = is.readLine();
os.println(line);
}
}
catch (IOException e) {
System.out.println(e);
}
}
}

19 :: What is Socket Programming?

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:

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.

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.

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.

20 :: What this function socketpair() does?

Socket Creation Using socketpair()
#include <sys/types.h>
#include <sys/socket.h>

int socketpair(int af, int type, int protocol, int sv[2])

socketpair() results in the creation of two connected sockets. sv[] is the array where the file descriptors for the sockets are returned. Each descriptor in sv[] is associated with one end of the communications link. Each descriptor can be used for both input and output. This means that full two-way communication between a parent process and one child process is possible.

Normally, one descriptor is reserved for use by a parent process and the other descriptor is used by a child process. The parent process closes the descriptor used by the child process. Conversely, the child process closes the descriptor used by the parent process. fork() is still required to pass one of the sockets to a child.

af represents the domain or address family to which the socket belongs. type is the type of socket to create.

Domains refer to the area where the communicating processes exist. Commonly used domains include:

* AF_UNIX for communication between processes on one system;
* AF_INET for communication between processes on the same or different systems using the DARPA standard protocols (IP/UDP/TCP).

Socket type refers to the "style" of communication. The two most commonly used values include:

* SOCK_STREAM: A stream of data with no record boundaries. Delivery in a networked environment is guaranteed; if delivery is impossible, the sender receives an error indicator.
* SOCK_DGRAM: A stream of records, each of a given size. Delivery in a networked environment is not guaranteed.

A protocol value of 0 is very common. This permits the system to choose the first protocol which is permitted with the pair of values specified for family and type.

Sample Code
#define DATA1 "test string 1"
#define DATA2 "test string 2"

#include <sys/types.h>

#include <sys/socket.h>
#include <stdio.h>
#include <errno.h>

main()
{
int sockets[2], child;
char buf[1024];

/* Get the socket pair */
if (socketpair(AF_UNIX, SOCK_STREAM,
0, sockets) < 0) {
printf("error %d on socketpairn", errno);
exit(1);
}

/* create child process */
if ((child = fork()) == -1) {
printf("fork error %dn", errno);
exit(1);
}

if (child != 0) { /* this is the parent */
/* close child's end of socket */
close(sockets[0]);

/* read message from child */
if (read(sockets[1], buf, sizeof(buf)) < 0) {
printf("error %d reading socketn", errno);
exit(1);
}
printf("-->%sn", buf);

/* write message to child */
if (write(sockets[1],
DATA1, sizeof(DATA1)) < 0) {
printf("error %d writing socketn", errno);
exit(1);
}

/* finished */
close(sockets[1]);

} else { /* the child */

/* close parent's end of socket */
close(sockets[1]);

/* send message to parent */
if (write(sockets[0], DATA2,
sizeof(DATA1)) < 0) {

printf("error %d writing socketn", errno);
exit(1);
}

/* get message from parent */

if (read(sockets[0],
buf, sizeof(buf)) < 0) {
printf("error %d reading socketn", errno);
exit(1);
}
printf("-->%sn", buf);

/* finished */
close(sockets[0]);
}
}

21 :: What this function socket() does?

Socket Creation Using socket()

#include <sys/types.h>
#include <sys/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.

22 :: What this function bind() does?

Giving a Socket a Name - bind()

#include <sys/types.h>
#include <sys/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);

23 :: What this function connect() does?

Specifying a Remote Socket - connect()

#include <sys/types.h>
#include <sys/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);
}

24 :: What this function sendto() does?

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);
}

25 :: What this function recvfrom() does?

Receiving on a Named Socket - recvfrom()

#include <sys/types.h>
#include <sys/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.