Top 100+ Socket Programming Interview Questions And Answers
Question 1. What Is Socket?
Answer :
A socket is one stop-point of a two-way communication hyperlink among two programs going for walks on the community. Socket classes are used to symbolize the connection among a client program and a server application. The java.Internet bundle gives two classes--Socket and ServerSocket--that implement the purchaser aspect of the relationship and the server facet of the connection, respectively.
Question 2. How Does The Race Condition Occur?
Answer :
It takes place whilst two or greater procedures are studying or writing some shared statistics and the very last end result relies upon on who runs precisely whilst.
UML Interview Questions
Question 3. What Is Multiprogramming?
Answer :
Multiprogramming is a speedy switching of the CPU back and forth among processes.
Question 4. Name The Seven Layers Of The Osi Model And Describe Them Briefly?
Answer :
Physical Layer - covers the physical interface among devices and the policies with the aid of which bits are surpassed from one to another.
Data Link Layer - attempts o make the bodily link dependable and offers the way to activate, maintain, and deactivate the link.
Network Layer - offers for the transfer of information between give up systems throughout some type communications network.
Transport Layer - affords a mechanism for the change of information among quit gadget.
Session Layer - presents the mechanism for controlling the speak among applications in give up systems.
Presentation Layer - defines the layout of the facts to be exchanged among packages and offers application programs a set of data transformation offerings.
Application Layer - offers a means for application programs to access the OSI surroundings.
UML Tutorial
Question five. What Is The Difference Between Tcp And Udp?
Answer :
TCP and UDP are each shipping-stage protocols. TCP is designed to offer reliable communication across a variety of dependable and unreliable networks and internets.
UDP offers a connectionless carrier for utility-degree procedures. Thus, UDP is essentially an unreliable provider; shipping and duplicate protection are not guareented.
Python Interview Questions
Question 6. What Does A Socket Consists Of?
Answer :
The mixture of an IP address and a port quantity is known as a socket.
Question 7. What Is A Javabean?
Answer :
JavaBeans are reusable software program additives written in the Java programming language, designed to be manipulated visually by using a software develpoment environment, like JBuilder or VisualAge for Java. They are much like Microsoft’s ActiveX additives, however designed to be platform-impartial, strolling everywhere there's a Java Virtual Machine (JVM).
Python Tutorial C++ Interview Questions
Question 8. What Are The Seven Layers(osi Model) Of Networking?
Answer :
Physical,
Data Link,
Network,
Transport,
Session,
Presentation and
Application Layers.
Question 9. What Are Some Advantages And Disadvantages Of Java Sockets?
Answer :
Advantages of Java Sockets:
Sockets are bendy and enough. Efficient socket based programming may be effortlessly applied for trendy communications.
Sockets cause low network site visitors. Unlike HTML bureaucracy and CGI scripts that generate and switch complete net pages for each new request, Java applets can send handiest essential updated records.
Disadvantages of Java Sockets:
Security regulations are occasionally overbearing due to the fact a Java applet walking in a Web browser is best capable of set up connections to the system in which it came from, and to nowhere else on the network
Despite all of the useful and helpful Java features, Socket based totally communications lets in handiest to ship packets of raw statistics among packages. Both the customer-facet and server-side should provide mechanisms to make the facts useful in any manner.
Since the facts formats and protocols continue to be utility unique, the re-use of socket primarily based implementations is restrained.
PHP Interview Questions
Question 10. What Is The Difference Between A Null Pointer And A Void Pointer?
Answer :
A NULL pointer is a pointer of any kind whose value is zero. A void pointer is a pointer to an item of an unknown kind, and is guaranteed to have enough bits to preserve a pointer to any object. A void pointer is not assured to have sufficient bits to point to a feature (even though in fashionable exercise it does).
C++ Tutorial
Question 11. What Is Encapsulation Technique?
Answer :
Hiding facts inside the elegance and making it to be had only through the methods. This technique is used to guard your elegance in opposition to unintended adjustments to fields, which might go away the elegance in an inconsistent nation.
Android Interview Questions
Question 12. How Do I Open A Socket?
Answer :
If you're programming a customer, you then could open a socket like this:
Socket MyClient;
MyClient = new Socket("Machine name", PortNumber);
Where Machine call is the device you are trying to open a connection to, and PortNumber is the port (a number) on which the server you are trying to connect with is strolling. When choosing a port wide variety, you should be aware that port numbers among zero and 1,023 are reserved for privileged customers (that is, exquisite consumer or root). These port numbers are reserved for standard offerings, which includes email, FTP, and HTTP. When choosing a port variety in your server, choose one this is greater than 1,023!
In the instance above, we didn't employ exception managing, however, it is a good idea to deal with exceptions. (From now on, all our code will deal with exceptions!) The above may 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 implementing a server you furthermore mght need to create a socket object from the ServerSocket for you to concentrate for and take delivery of connections from customers.
Socket clientSocket = null;
try
serviceSocket = MyService.Take delivery of();
catch (IOException e)
System.Out.Println(e);
UML Interview Questions
Question thirteen. How Do I Create An Input Stream?
Answer :
On the purchaser aspect, you may use the DataInputStream magnificence to create an input stream to acquire reaction from the server:
DataInputStream input;
strive
input = new DataInputStream(MyClient.GetInputStream());
trap (IOException e)
System.Out.Println(e);
The magnificence DataInputStream lets in you to examine traces of text and Java primitive statistics kinds in a portable manner. It has methods which includes read, readChar, readInt, readDouble, and readLine,. Use whichever function you think suits your desires depending at the type of facts that you receive from the server.
On the server facet, you can use DataInputStream to acquire input from the patron:
DataInputStream enter;
strive
enter = new DataInputStream(serviceSocket.GetInputStream());
seize (IOException e)
System.Out.Println(e);
PHP Tutorial
Question 14. How Do I Create An Output Stream?
Answer :
On the consumer aspect, you may create an output movement to ship statistics to the server socket the usage of the elegance PrintStream or DataOutputStream of java.Io:
PrintStream output;
strive
output = new PrintStream(MyClient.GetOutputStream());
trap (IOException e)
System.Out.Println(e);
The class PrintStream has strategies for showing textual representation of Java primitive records kinds. Its Write and println techniques are crucial here. Also, you can need to use the DataOutputStream:
DataOutputStream output;
attempt
output = new DataOutputStream(MyClient.GetOutputStream());
catch (IOException e)
System.Out.Println(e);
The magnificence DataOutputStream allows you to jot down Java primitive information sorts; many of its techniques write a single Java primitive kind to the output movement. The technique writeBytes is a beneficial one.
On the server aspect, you may use the elegance PrintStream to send facts to the consumer.
PrintStream output;
try
output = new PrintStream(serviceSocket.GetOutputStream());
seize (IOException e)
System.Out.Println(e);
Note: You can use the class DataOutputStream as mentioned above.
Question 15. How Do I Close Sockets?
Answer :
You must continually near the output and input circulate before you close up the socket:
On the customer side:
attempt
output.Near();
input.Near();
MyClient.Near();
capture (IOException e)
System.Out.Println(e);
On the server facet:
try
output.Close();
enter.Close();
serviceSocket.Close();
MyService.Close();
catch (IOException e)
System.Out.Println(e);
Basic Programming Interview Questions
Question sixteen. Explain Data Transfer Over Connected Sockets - Send() And Recv()?
Answer :
Two additional statistics transfer library calls, specifically ship() and recv(), are available if the sockets are related. They correspond very closely to the examine() and write() functions used for I/O on regular record descriptors.
#consist of <ltsys/types.H>
#encompass <ltsys/socket.H>
int send(int sd, char *buf, int len, int flags)
int recv(int sd, char * buf, int len, int flags)
In each cases, sd is the socket descriptor. For send(), buf factors to a buffer containing the records to be sent, len is the duration of the information and flags will generally be 0. The go back fee is the quantity of bytes sent if a success. If now not a hit, -1 is again and errno describes the error.
For recv(), buf factors to a information place into which the acquired data is copied, len is the size of this information region in bytes, and flags is generally both 0 or set to MSG_PEEK if the received facts is to be retained in the gadget after it's miles obtained. The go back cost is the number of bytes received if a success. If not a success, -1 is again and errno describes the error.
Android Tutorial
Question 17. Explain Connection Establishment By Server - Accept()?
Answer :
#encompass <ltsys/types.H>
#consist of <ltsys/socket.H>
int accept(int sockfd, struct sockaddr *name,int *namelen)
The be given() name establishes a client-server connection at the server facet. (The purchaser requests the connection the usage of the connect() device name.) The server must have created the socket the usage of socket(), given the socket a call the usage of bind(), and established a listen queue the usage of concentrate().
Sockfd is the socket record descriptor back from the socket() device 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 successful return from take delivery of(), this structure will contain the protocol deal with of the customer's socket. The statistics vicinity pointed to via namelen ought to be initialized to the real length of call. Upon a success go back from be given, the information region pointed to with the aid of namelen will incorporate the real duration of the protocol address of the consumer's socket.
If a hit, take delivery of() creates a new socket of the identical family, kind, and protocol as sockfd. The record descriptor for this new socket is the return cost of receive(). This new socket is used for all communications with the purchaser.
If there's no customer connection request waiting, receive() will block until a purchaser request is queued.
Accept() will fail mainly if sockfd isn't always a document descriptor for a socket or if the socket kind is not SOCK_STREAM. In this case, accept() returns the cost -1 and errno describes the trouble.
Java-Multithreading Interview Questions
Question 18. How To Make A Socket A Listen-most effective Connection Endpoint - Listen()?
Answer :
/*
Code Sample: Make a Socket a Listen-only
Connection Endpoint - pay attention()
by using GlobalGuideline.Com*/
#encompass <ltsys/types.H>
#consist of <ltsys/socket.H>
int concentrate(int s, int backlog)
/*
concentrate establishes the socket as a passive
endpoint of a connection. It does now not suspend system execution.
*/
/*
No messages can be sent thru this socket.
Incoming messages may be received.
*/
/*
s is the record descriptor related to the socket created the use of the socket() gadget name. Backlog is the dimensions of the queue of ready requests whilst the server is busy with a provider request. The current device-imposed most value is 5.
*/
/*
zero is returned on success, -1 on mistakes with errno indicating the hassle.
*/
Example:
#include <ltsys/types.H>
#include <ltsys/socket.H>
int sockfd; /* socket document descriptor */
if(pay attention(sockfd, 5) < 0)
printf ("pay attention mistakes %dn", errno);
Python Interview Questions
Question 19. How Sockets Can Be Used To Write Client-server Applications Using A Connection-oriented Client-server Technique?
Answer :
Sockets can be used to jot down purchaser-server packages the usage of a connection-orientated patron-server method. Some traits of this approach consist of:
The server can manage more than one customer requests for connection and carrier.
The server responds to anybody purchaser's request independently of all different customers.
A patron is aware of how to set up a connection with the server.
The patron-server connection, whilst installed, stays in life until either the purchaser or the server explicitly breaks it, much like a hassle-unfastened cellphone call. The socket used for this connection is known as a connection-oriented socket.
The socket kind is specified as SOCK_STREAM. As a end result, the system receiving a message strategies that message with the aid of the following rules:
The statistics transmitted has no barriers.
All bytes in a obtained message ought to be read before the subsequent message can be processed.
Bytes in a received message may be read in a loop application manipulate structure for the reason that no information bytes are discarded.
The server will usually fork() a child manner upon established order of a patron connection.
This toddler server manner is designed to speak with exactly one patron procedure.
The child server procedure performs the asked service for its linked patron.
The infant server technique terminates while the service request has been finished.
Functions pay attention() and receive() permit the server to concentrate for service requests. Study() and write() may be utilized by patron and server to send/get hold of messages; ship() and recv() may also be used.
Node.Js Tutorial
Question 20. How To Disposing Of A Socket?
Answer :
Code Sample: How to getting rid of a Socket :
#include <ltstdio.H>
void close(int s).
/* The I/O call near() will near the socket descriptor s just as it closes any open document descriptor.
Example - sendto() and recvfrom()
*/
/* receiver */
#encompass <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);
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);
go out(1);
cnt = recvfrom(sock, buf, sizeof(buf),
zero, &from_name, &fromlen);
if (cnt < zero)
printf("recvfrom failure %dn", errno);
exit(1);
buf[cnt] = ''; /* guarantee null byte */
from_name.Sa_data[fromlen] = '';
printf("'%s' received from %sn",
buf, from_name.Sa_data);
/* sender */
#encompass <ltsys/types.H>
#include <ltsys/socket.H>
char buf[80];
struct sockaddr to_name;
main()
int sock;
sock = socket(AF_UNIX, SOCK_DGRAM, zero);
if (sock < zero)
printf("socket failure %dn", errno);
go out(1);
to_name.Sa_family = AF_UNIX;
strcpy(to_name.Sa_data, "/tmp/tsck");
strcpy(buf, "take a look at records 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);
go out(1);
Node.Js Interview Questions
Question 21. What This Function Recvfrom() Does?
Answer :
Receiving on a Named Socket - recvfrom()
#encompass <ltsys/types.H>
#consist of <ltsys/socket.H>
int recvfrom(int s, char *msg, int len, int flags,struct sockaddr *from, int *fromlen)
This feature permits a message msg of maximum period len to be study from a socket with descriptor s from the socket named by using from and fromlen, where fromlen is the actual duration of from. The variety of characters absolutely study from the socket is the go back cost of the function. On errors, -1 is back and errno describes the error. Flags may be zero, or might also specify MSG_PEEK to look at a message with out sincerely receiving it from the queue.
If no message is available to be read, the process will droop looking forward to one except the socket is ready to nonblocking mode (via an ioctl name).
The system I/O name examine() also can be used to read statistics from a socket.
Question 22. What This Function Sendto() Does?
Answer :
Sending to a Named Socket - sendto()
int sendto(int s, char *msg, int len, int flags, struct sockaddr *to, int tolen)
This characteristic allows a message msg of duration len to be despatched on a socket with descriptor s to the socket named via to and tolen, wherein tolen is the real length of to. Flags will continually be zero for our purposes. The quantity of characters despatched is the return cost of the characteristic. On error, -1 is returned 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)) < zero)
printf("send failuren");
exit(1);
Javascript Advanced Tutorial
Question 23. What This Function Connect() Does?
Answer :
Specifying a Remote Socket - connect()
#consist of <ltsys/types.H>
#include <ltsys/socket.H>
int join(int s, struct sockaddr *name, int namelen)
The bind() call only permits specification of a nearby cope with. To specify the far flung side of an address connection the join() name is used. In the call to connect, s is the document descriptor for the socket. Name is a pointer to a structure of kind sockaddr:
struct sockaddr
u_short sa_family;
char sa_data[14];
;
As with the bind() machine call, name.Sa_family should be AF_UNIX. Name.Sa_data have to include up to 14 bytes of a file call which will be assigned to the socket. Namelen offers the real duration of call. A go back cost of 0 indicates achievement, at the same time as a fee of -1 shows failure with errno describing the error.
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("join failure %dn", errno);
Javascript Advanced Interview Questions
Question 24. What This Function Bind() Does?
Answer :
Giving a Socket a Name - bind()
#consist of <ltsys/types.H>
#encompass <ltsys/socket.H>
int bind(int s, struct sockaddr *name, int namelen)
Recall that, using socketpair(), sockets could only be shared among determine and infant approaches or children of the identical parent. With a name connected to the socket, any technique on the device can describe (and use) it.
In a call to bind(), s is the document descriptor for the socket, acquired from the decision to socket(). Call is a pointer to a structure of type sockaddr. If the cope with circle of relatives is AF_UNIX (as precise while the socket is created), the structure is defined as follows:
struct sockaddr
u_short sa_family;
char sa_data[14];
;
name.Sa_family ought to be AF_UNIX. Call.Sa_data need to incorporate up to 14 bytes of a record call if you want to be assigned to the socket. Namelen offers the real length of call, that is, the length of the initialized contents of the statistics shape.
A fee of zero is go back on achievement. On failure, -1 is again with errno describing the error.
Example:
struct sockaddr call;
int s;
name.Sa_family = AF_UNIX;
strcpy(call.Sa_data, "/tmp/sock");
if((s = socket(AF_UNIX, SOCK_STREAM, 0) < 0)
printf("socket create failure %dn", errno);
go out(zero);
if (bind(s, &name, strlen(call.Sa_data) +
sizeof(call.Sa_family)) < zero)
printf("bind failure %dn", errno);
C++ Interview Questions
Question 25. What This Function Socket() Does?
Answer :
Socket Creation Using socket()
#consist of <ltsys/types.H>
#consist of <ltsys/socket.H>
int socket(int af, int kind, int protocol)
socket() could be very similar to socketpair() except that only one socket is created instead of two. This is maximum typically used if the procedure you wish to talk with isn't always a toddler process. The af, kind, and protocol fields are used simply as within the socketpair() machine name.
On achievement, a document descriptor to the socket is returned. On failure, -1 is lower back and errno describes the hassle.
Dynamic Link Library (DLL) Tutorial
Question 26. What Is Socket Programming?
Answer :
Sockets are a generalized networking capability first introduced in four.1cBSD and finally subtle into their cutting-edge form with four.2BSD. The sockets feature is available with most modern-day UNIX machine releases. (Transport Layer Interface (TLI) is the System V opportunity). Sockets permit communique between special techniques on the identical or distinct machines. Internet protocols are used by default for communique among machines; different protocols inclusive of DECnet may be used if they are available.
To a programmer a socket looks and behaves much like a low degree document descriptor. This is due to the fact instructions which include study() and write() work with sockets in the equal manner they do with files and pipes. The variations between sockets and regular record descriptors takes place within the creation of a socket and thru an expansion of unique operations to control a socket. These operations are distinctive among sockets and normal document descriptors because of the extra complexity in establishing community connections while compared with normal disk get entry to.
For most operations using sockets, the jobs of purchaser and server ought to be assigned. A server is a procedure which does some characteristic on request from a client. As could be visible on this discussion, the jobs aren't symmetric and can not be reversed without a few attempt.
This description of the use of sockets progresses in 3 stages:
The use of sockets in a connectionless or datagram mode between patron and server procedures at the equal host. In this situation, the purchaser does now not explicitly set up a connection with the server. The patron, of course, should recognise the server's deal with. The server, in turn, surely waits for a message to show up. The consumer's deal with is one of the parameters of the message acquire request and is used by the server for response.
The use of sockets in a related mode among client and server at the identical host. In this case, the jobs of customer and server are similarly bolstered by way of the manner wherein the socket is hooked up and used. This version is often known as a connection-orientated purchaser-server version.
The use of sockets in a linked mode among purchaser 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 isn't always explicitly discussed here. Its use may be inferred from the displays made in Stages 1 and three.
Unix Inter-Process Communication (IPC) Interview Questions
