YouTube Icon

Interview Questions.

Top 26 Socket Programming Interview Questions - Jul 28, 2022

fluid

Top 26 Socket Programming Interview Questions

Q1. What This Function Connect() Does?

Specifying a Remote Socket - connect()

#encompass <ltsys/types.H>

#include <ltsys/socket.H>

int connect(int s, struct sockaddr *name, int namelen)

 

The bind() name simplest lets in specification of a neighborhood cope with. To specify the faraway aspect of an address connection the join() call is used. In the decision to attach, s is the document 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() gadget call, name.Sa_family ought to be AF_UNIX. Call.Sa_data should incorporate up to 14 bytes of a record name if you want to be assigned to the socket. Namelen offers the real duration of name. A return price of zero shows success, whilst a price of -1 shows failure with errno describing the mistake.

A pattern code fragment:

struct sockaddr name;

call.Sa_family = AF_UNIX;

strcpy(call.Sa_data, "/tmp/sock");

if (connect(s, &call, strlen

(name.Sa_data) +

sizeof(name.Sa_family)) < 0) 

printf("connect failure %dn", errno);

 

Q2. What This Function Socket() Does?

Socket Creation Using socket()

#encompass <ltsys/types.H>

#include <ltsys/socket.H>

int socket(int af, int type, int protocol)

socket() is very similar to socketpair() except that simplest one socket is created as opposed to two. This is most generally used if the procedure you want to talk with is not a baby process. The af, kind, and protocol fields are used just as within the socketpair() system name.

On fulfillment, a document descriptor to the socket is back. On failure, -1 is lower back and errno describes the hassle.

Q3. What Does A Socket Consists Of?

The combination of an IP cope with and a port wide variety is known as a socket.

Q4. Explain Connection Establishment By Server - Accept()?

#consist of <ltsys/types.H>

#include <ltsys/socket.H>

int accept(int sockfd, struct sockaddr *call,int *namelen)

The be given() name establishes a purchaser-server connection at the server aspect. (The client requests the relationship the use of the join() gadget call.) The server should have created the socket the usage of socket(), given the socket a call using bind(), and established a listen queue the usage of pay attention().

Sockfd is the socket document descriptor back from the socket() system name. Call is a pointer to a shape of kind sockaddr as defined above

struct sockaddr 

u_short sa_family;

char sa_data[14];

;

Upon a hit go back from be given(), this shape will comprise the protocol address of the client's socket. The records vicinity pointed to by using namelen ought to be initialized to the real period of name. Upon successful go back from take delivery of, the records place pointed to with the aid of namelen will contain the real period of the protocol address of the consumer's socket.

If a hit, be given() creates a new socket of the same circle of relatives, kind, and protocol as sockfd. The file descriptor for this new socket is the go back price of be given(). This new socket is used for all communications with the patron.

If there is no customer connection request waiting, take delivery of() will block until a client request is queued.

Receive() will fail specially if sockfd isn't always a document descriptor for a socket or if the socket kind isn't SOCK_STREAM. In this case, be given() returns the fee -1 and errno describes the trouble.

Q5. How Sockets Can Be Used To Write Client-server Applications Using A Connection-oriented Client-server Technique?

Sockets can be used to jot down customer-server applications the usage of a connection-orientated purchaser-server method. Some characteristics of this approach include:

The server can take care of multiple consumer requests for connection and service.

The server responds to anyone patron's request independently of all other clients.

A purchaser is aware of a way to set up a connection with the server.

The consumer-server connection, while installed, stays in existence till either the consumer or the server explicitly breaks it, much like a problem-unfastened phone call. The socket used for this connection is called a connection-oriented socket.

The socket type is distinct as SOCK_STREAM. As a end result, the system receiving a message techniques that message through the following rules:

The data transmitted has no barriers.

All bytes in a obtained message should be read earlier than the next message can be processed.

Bytes in a obtained message can be examine in a loop program manipulate shape considering no facts bytes are discarded.

The server will usually fork() a infant process upon status quo of a patron connection.

This toddler server procedure is designed to speak with precisely one consumer process.

The child server system performs the asked provider for its linked patron.

The baby server method terminates whilst the carrier request has been completed.

Functions listen() and receive() allow the server to pay attention for provider requests. Study() and write() may be utilized by patron and server to ship/get hold of messages; send() and recv() can also be used.

Q6. What Is The Difference Between Tcp And Udp?

TCP and UDP are each shipping-degree protocols. TCP is designed to offer dependable communication across a variety of reliable and unreliable networks and internets.

UDP offers a connectionless service for application-degree procedures. Thus, UDP is essentially an unreliable service; shipping and replica protection are not guareented.

Q7. How Do I Open A Socket?

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

Socket MyClient;

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

Where Machine call is the system you are attempting to open a connection to, and PortNumber is the port (more than a few) on which the server you are trying to hook up with is going for walks. When selecting a port range, you should notice that port numbers between zero and 1,023 are reserved for privileged customers (this is, tremendous user or root). These port numbers are reserved for trendy offerings, along with electronic mail, FTP, and HTTP. When selecting a port quantity for your server, select one this is greater than 1,023!

In the instance above, we failed to employ exception dealing with, but, it is a great idea to deal with exceptions. (From now on, all our code will take care of exceptions!) The above can be written as:

Socket MyClient;

strive 

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

seize (IOException e) 

System.Out.Println(e);

If you're programming a server, then that is the way you open a socket:

ServerSocket MyService;

attempt 

MyServerice = new ServerSocket(PortNumber);

trap (IOException e) 

System.Out.Println(e);

When enforcing a server you furthermore mght need to create a socket object from the ServerSocket so one can pay attention for and receive connections from clients.

Socket clientSocket = null;

try 

serviceSocket = MyService.Receive();

seize (IOException e) 

System.Out.Println(e);

 

Q8. What This Function Bind() Does?

Giving a Socket a Name - bind()

#include <ltsys/types.H>

#include <ltsys/socket.H>

int bind(int s, struct sockaddr *call, int namelen)

Recall that, the use of socketpair(), sockets could best be shared between parent and baby processes or youngsters of the equal figure. With a call connected to the socket, any method on the device can describe (and use) it.

In a name to bind(), s is the report descriptor for the socket, acquired from the decision to socket(). Name is a pointer to a shape of type sockaddr. If the deal with family is AF_UNIX (as special while the socket is created), the shape is described as follows:

struct sockaddr 

u_short sa_family;

char sa_data[14];

;

call.Sa_family ought to be AF_UNIX. Call.Sa_data should include up to 14 bytes of a report call in an effort to be assigned to the socket. Namelen gives the actual period of call, that is, the period of the initialized contents of the records structure.

A price of zero is return on fulfillment. On failure, -1 is lower back with errno describing the mistake.

Example:

struct sockaddr name;

int s;

name.Sa_family = AF_UNIX;

strcpy(call.Sa_data, "/tmp/sock");

if((s = socket(AF_UNIX, SOCK_STREAM, zero) < 0)

printf("socket create failure %dn", errno);

exit(zero);

if (bind(s, &call, strlen(name.Sa_data) +

sizeof(call.Sa_family)) < zero)

printf("bind failure %dn", errno);

 

Q9. How To Make A Socket A Listen-most effective Connection Endpoint - Listen()?

/*

Code Sample: Make a Socket a Listen-simplest

Connection Endpoint - pay attention()

by using GlobalGuideline.Com*/

#consist of <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 droop system execution.

*/

/* 

No messages may be sent through this socket.

Incoming messages may be acquired.

*/

/*

s is the document descriptor associated with the socket created using the socket() system call. Backlog is the size of the queue of waiting requests even as the server is busy with a carrier request. The modern-day system-imposed most price is five.

*/

/*

zero is lower back on achievement, -1 on blunders with errno indicating the hassle.

*/

Example:

#include <ltsys/types.H>

#consist of <ltsys/socket.H>

int sockfd; /* socket document descriptor */

if(concentrate(sockfd, five) < 0)

printf ("concentrate errors %dn", errno);

Q10. 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 characteristic permits a message msg of length len to be sent on a socket with descriptor s to the socket named by way of to and tolen, wherein tolen is the real period of to. Flags will always be 0 for our purposes. The range of characters sent is the return fee of the function. On mistakes, -1 is again and errno describes the mistake.

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

zero, &to_name,

strlen(to_name.Sa_data) +

sizeof(to_name.Sa_family)) < 0) 

printf("send failuren");

go out(1);

 

Q11. What This Function Recvfrom() Does?

Receiving on a Named Socket - recvfrom()

#include <ltsys/types.H>

#encompass <ltsys/socket.H>

int recvfrom(int s, char *msg, int len, int flags,struct sockaddr *from, int *fromlen)

This characteristic lets in a message msg of maximum length len to be study from a socket with descriptor s from the socket named by way of from and fromlen, in which fromlen is the actual duration of from. The range of characters definitely study from the socket is the return fee of the feature. On error, -1 is lower back and errno describes the mistake. Flags can be 0, or may also specify MSG_PEEK to have a look at a message with out honestly receiving it from the queue.

If no message is available to be study, the procedure will droop looking ahead to one until the socket is about to nonblocking mode (via an ioctl name).

The gadget I/O name read() can also be used to study information from a socket.

Q12. How Do I Close Sockets?

You should constantly near the output and enter flow before you close the socket:

On the customer facet:

try 

output.Close();

enter.Near();

MyClient.Close();

capture (IOException e) 

System.Out.Println(e);

On the server facet:

strive 

output.Close();

input.Close();

serviceSocket.Near();

MyService.Near();

seize (IOException e) 

System.Out.Println(e);

 

Q13. How Does The Race Condition Occur?

It occurs whilst  or extra approaches are reading or writing some shared information and the very last result relies upon on who runs precisely when.

Q14. How To Disposing Of A Socket?

Code Sample: How to eliminating a Socket :

#encompass <ltstdio.H>

void close(int s).

/* The I/O call close() will close the socket descriptor s just because it closes any open document descriptor.

Example - sendto() and recvfrom()

*/

/* receiver */

#encompass <ltsys/types.H>

#encompass <ltsys/socket.H>

struct sockaddr myname;

struct sockaddr from_name;

char buf[80];

most important()

int sock;

int fromlen, cnt;

sock = socket(AF_UNIX, SOCK_DGRAM, zero);

if (sock < 0) 

printf("socket failure %dn", errno);

go out(1);

myname.Sa_family = AF_UNIX;

strcpy(myname.Sa_data, "/tmp/tsck");

if (bind(sock, &myname,

strlen(myname.Sa_data) +

sizeof(name.Sa_family)) < zero) 

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

go out(1);

buf[cnt] = ''; /* guarantee null byte */

from_name.Sa_data[fromlen] = '';

printf("'%s' acquired from %sn",

buf, from_name.Sa_data);

 

/* sender */

#include <ltsys/types.H>

#consist of <ltsys/socket.H>

char buf[80];

struct sockaddr to_name;

most important()

int sock;

sock = socket(AF_UNIX, SOCK_DGRAM, 0);

if (sock < zero) 

printf("socket failure %dn", errno);

exit(1);

 

to_name.Sa_family = AF_UNIX;

strcpy(to_name.Sa_data, "/tmp/tsck");

strcpy(buf, "take a look at information line");

cnt = sendto(sock, buf, strlen(buf),

0, &to_name,

strlen(to_name.Sa_data) + sizeof(to_name.Sa_family));

if (cnt < zero) 

printf("sendto failure %dn", errno);

exit(1);

Q15. Explain Data Transfer Over Connected Sockets - Send() And Recv()?

Two extra information transfer library calls, particularly ship() and recv(), are to be had if the sockets are related. They correspond very carefully to the examine() and write() features used for I/O on everyday report descriptors.

#encompass <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 instances, sd is the socket descriptor. For send(), buf points to a buffer containing the statistics to be sent, len is the period of the records and flags will normally be @The return value is the wide variety of bytes sent if a success. If not a hit, -1 is lower back and errno describes the mistake.

For recv(), buf points to a facts vicinity into which the received information is copied, len is the size of this statistics area in bytes, and flags is typically either zero or set to MSG_PEEK if the received records is to be retained in the machine after it is obtained. The return price is the variety of bytes received if successful. If not a success, -1 is again and errno describes the mistake. 

Q16. How Do I Create An Input Stream?

On the consumer facet, you could use the DataInputStream class to create an enter stream to receive reaction from the server:

DataInputStream enter;

attempt 

enter = new DataInputStream(MyClient.GetInputStream());

capture (IOException e) 

System.Out.Println(e);

The class DataInputStream allows you to read traces of text and Java primitive records types in a portable manner. It has techniques together with read, readChar, readInt, readDouble, and readLine,. Use whichever function you think fits your desires relying on the kind of information which you receive from the server.

On the server side, you can use DataInputStream to acquire input from the patron:

DataInputStream input;

attempt 

input = new DataInputStream(serviceSocket.GetInputStream());

seize (IOException e) 

System.Out.Println(e);

 

Q17. How Do I Create An Output Stream?

On the purchaser aspect, you may create an output circulation to ship records to the server socket using the elegance PrintStream or DataOutputStream of java.Io:

PrintStream output;

attempt 

output = new PrintStream(MyClient.GetOutputStream());

seize (IOException e) 

System.Out.Println(e);

 

The elegance PrintStream has strategies for displaying textual representation of Java primitive data sorts. Its Write and println techniques are important right here. Also, you can need to use the DataOutputStream:

DataOutputStream output;

strive 

output = new DataOutputStream(MyClient.GetOutputStream());

trap (IOException e) 

System.Out.Println(e);

 

The class DataOutputStream permits you to write down Java primitive records sorts; many of its strategies write a single Java primitive type to the output stream. The approach writeBytes is a beneficial one.

On the server side, you could use the elegance PrintStream to send records to the patron.

PrintStream output;

strive 

output = new PrintStream(serviceSocket.GetOutputStream());

catch (IOException e) 

System.Out.Println(e);

 

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

Q18. What Is Encapsulation Technique?

Hiding information in the class and making it to be had only through the strategies. This approach is used to protect your class towards unintentional changes to fields, which would possibly depart the elegance in an inconsistent kingdom.

Q19. What Are The Seven Layers(osi Model) Of Networking?

Physical,

Data Link,

Network,

Transport,

Session,

Presentation and

Application Layers.

Q20. What Is A Javabean?

JavaBeans are reusable software additives written in the Java programming language, designed to be manipulated visually by way of a software program develpoment surroundings, like JBuilder or VisualAge for Java. They are much like Microsoft’s ActiveX additives, but designed to be platform-impartial, running anywhere there's a Java Virtual Machine (JVM).

Q21. What Is Multiprogramming?

Multiprogramming is a rapid switching of the CPU to and fro among procedures.

Q22. What Is Socket Programming?

Sockets are a generalized networking capability first added in 4.1cBSD and subsequently subtle into their cutting-edge form with 4.2BSD. The sockets characteristic is to be had with most cutting-edge UNIX device releases. (Transport Layer Interface (TLI) is the System V opportunity). Sockets permit communication among two special methods at the identical or extraordinary machines. Internet protocols are utilized by default for conversation among machines; different protocols such as DECnet may be used if they're to be had.

To a programmer a socket seems and behaves similar to a low degree report descriptor. This is because commands together with read() and write() paintings with sockets inside the identical way they do with documents and pipes. The differences between sockets and everyday record descriptors takes place in the advent of a socket and through a ramification of unique operations to control a socket. These operations are distinct among sockets and ordinary record descriptors due to the additional complexity in setting up network connections whilst in comparison with regular disk get entry to.

For most operations the usage of sockets, the roles of purchaser and server should be assigned. A server is a method which does a few feature on request from a purchaser. As might be visible in this dialogue, the jobs aren't symmetric and can not be reversed without some attempt.

This description of the usage of sockets progresses in 3 levels:

The use of sockets in a connectionless or datagram mode between patron and server approaches on the same host. In this case, the patron does no longer explicitly establish a connection with the server. The purchaser, of path, must understand the server's deal with. The server, in turn, without a doubt waits for a message to reveal up. The customer's address is one of the parameters of the message acquire request and is used by the server for response.

The use of sockets in a linked mode between purchaser and server at the identical host. In this example, the jobs of client and server are further strengthened by using the way wherein the socket is hooked up and used. This model is frequently known as a connection-oriented consumer-server model.

The use of sockets in a related mode between customer and server on exclusive hosts. This is the community extension of Stage 2, above.

The connectionless or datagram mode between patron and server on special hosts isn't always explicitly mentioned here. Its use may be inferred from the shows made in Stages 1 and 3.

Q23. What Is The Difference Between A Null Pointer And A Void Pointer?

A NULL pointer is a pointer of any kind whose fee is 0. A void pointer is a pointer to an item of an unknown kind, and is guaranteed to have enough bits to hold a pointer to any item. A void pointer isn't always guaranteed to have sufficient bits to point to a characteristic (even though in wellknown exercise it does).

Q24. What Is Socket?

A socket is one quit-factor of a two-manner communication hyperlink among two programs going for walks on the community. Socket training are used to symbolize the connection among a client program and a server program. The java.Internet bundle provides  instructions--Socket and ServerSocket--that put in force the customer aspect of the relationship and the server facet of the relationship, respectively.

Q25. What Are Some Advantages And Disadvantages Of Java Sockets?

Advantages of Java Sockets:

Sockets are bendy and sufficient. Efficient socket primarily based programming can be easily carried out for wellknown communications.

Sockets reason low network visitors. Unlike HTML paperwork and CGI scripts that generate and switch complete internet pages for each new request, Java applets can send only necessary up to date records.

Disadvantages of Java Sockets:

Security regulations are on occasion overbearing because a Java applet jogging in a Web browser is simplest capable of establish connections to the gadget wherein it got here from, and to nowhere else at the network

Despite all of the useful and beneficial Java features, Socket based totally communications permits best to send packets of uncooked information among applications. Both the customer-aspect and server-aspect need to provide mechanisms to make the statistics useful in any way.

Since the statistics codecs and protocols remain application specific, the re-use of socket primarily based implementations is restrained.

Q26. Name The Seven Layers Of The Osi Model And Describe Them Briefly?

Physical Layer - covers the bodily interface among gadgets and the guidelines via which bits are passed from one to some other.

Data Link Layer - tries o make the physical link dependable and offers the way to spark off, hold, and deactivate the link.

Network Layer - provides for the transfer of statistics among quit systems across a few kind communications network.

Transport Layer - offers a mechanism for the trade of data between quit device.

Session Layer - presents the mechanism for controlling the talk between packages in quit structures.

Presentation Layer - defines the format of the facts to be exchanged between programs and offers application programs a fixed of records transformation offerings.

Application Layer - offers a method for utility applications to get admission to the OSI environment.




CFG