Top 100+ Unix Socket Interview Questions And Answers
Question 1. How Do Sockets Work?
Answer :
The implementation is left up to the vendor of your specific unix, but from the factor of view of the programmer, connection-orientated sockets paintings loads like files, or pipes. The most major difference, once you have your file descriptor is that study() or write() calls may really read or write fewer bytes than asked. If this occurs, then you will must make a 2d call for the relaxation of the information. There are examples of this inside the supply code that accompanies the faq.
Question 2. What Is With The Second Parameter In Bind()?
Answer :
The guy page indicates it as "struct sockaddr *my_addr". The sockaddr struct although is simply an area holder for the structure it truly wishes. You must bypass one-of-a-kind structures depending on what kind of socket you have got. For an AF_INET socket, you need the sockaddr_in shape.
It has 3 fields of interest:
1.Sin_family
Set this to AF_INET.
2.Sin_port
The network byte-ordered sixteen bit port variety
3.Sin_addr
The host's ip range.
This is a struct in_addr,
which incorporates simplest one discipline,
s_addr which is a u_long.
Networking Interview Questions
Question three. If Bind() Fails, What Should I Do With The Socket Descriptor?
Answer :
If you're exiting, I have been assured through Andrew that every one unixes will close open report descriptors on exit. If you are not exiting even though, you may just close it with a normal near() call.
Question four. When Should I Use Shutdown()?
Answer :
shutdown() is useful for delineating whilst you are done supplying a request to a server using TCP. A regular use is to ship a request to a server followed by way of a shutdown(). The server will examine your request observed by way of an EOF (examine of zero on most unix implementations). This tells the server that it has your complete request. You then move examine blocked at the socket. The server will system your request and ship the essential records returned to you accompanied through a near. When you've got finished reading all the reaction on your request you may examine an EOF as a consequence signifying that you have the entire response. It must be mentioned the TTCP (TCP for Transactions -- see R. Steven's domestic web page) provides for a better approach of tcp transaction control.
Networking Tutorial
Question five. What Do We Expect?
Answer :
The baby detects an EOF from its stdin, it closes the socket (assuming connection smash) and exits. The server in its turn detects EOF, closes connection and exits. The parent detects EOF, makes the wait() gadget name and exits. What will we see as an alternative? The socket instance in the determine method continues to be opened for writing and studying, though the figure never writes. The server never detects EOF and waits for greater information from the client all the time. The determine by no means sees the relationship is closed and hangs for all time and the server hangs too. Unexpected impasse!
You need to change the patron fragment as follows:
if( fork() )
/* The infant */
even as( receives(buffer)
write(s,buffer,strlen(buffer));
shutdown(s,1);
/* Break the relationship
for writing, The server will detect EOF now.
Note: reading from the socket continues to be allowed.
The server may also ship a few extra statistics
after receiving EOF, why now not? */
go out(zero);
UNIX/XENIX Interview Questions
Question 6. What Are Sockets?
Answer :
Sockets are much like "worm holes" in technological know-how fiction. When matters go into one cease, they (ought to) come out of the other. Different kinds of sockets have distinctive properties. Sockets are both connection- oriented or connectionless. Connection-orientated sockets permit for statistics to waft to and fro as wished, whilst connectionless sockets (additionally referred to as datagram sockets) allow best one message at a time to be transmitted, without an open connection. There are also exceptional socket households. The maximum common are AF_INET for net connections, and AF_UNIX for unix IPC (interprocess communique). As stated in advance, this FAQ deals best with AF_INET sockets.
Question 7. How Can I Tell When A Socket Is Closed On The Other End?
Answer :
If the peer calls close() or exits, without having messed with SO_LINGER, then our calls to read() must go back 0. It is much less clean what occurs to jot down() calls in this case; I might count on EPIPE, not on the subsequent call, but the one after.
If the peer reboots, or sets l_onoff = 1,l_linger = zero after which closes, then we must get ECONNRESET (eventually) from examine(), or EPIPE from write().
When write() returns EPIPE, it additionally raises the SIGPIPE sign - you by no means see the EPIPE mistakes except you cope with or forget about the sign.
If the peer remains unreachable, we have to get a few other error.
Don't suppose that write() can legitimately go back zero. Read() need to go back zero on receipt of a FIN from the peer, and on all following calls.
So yes, you have to anticipate study() to return 0.
As an example, assume you are receiving a document down a TCP link; you may manage the go back from examine() like this:
rc = read(sock,buf,sizeof(buf));
if (rc > zero)
write(report,buf,rc);
/* mistakes checking on record neglected */
else if (rc == 0)
near(document);
close(sock);
/* document received efficaciously */
else /* rc < 0 */
/* close file and delete it, since data
is not complete report error, or whatever */
WebSockets Tutorial Java-Multithreading Interview Questions
Question 8. How Do I Get The Port Number For A Given Service?
Answer :
Use the getservbyname() routine. This will return a pointer to a servent structure. You are interested in the s_port field, which contains the port number, with correct byte ordering (so you don't need to call htons() on it). Here is a sample routine.
/* Take a service name, and a service type, and return a port number. If the service name is not found, it tries it as a decimal number. The number returned is byte ordered for the network. */
int atoport(char *service, char *proto)
int port;
long int lport;
struct servent *serv;
char *errpos;
/* First try to read it from /etc/services */
serv = getservbyname(service, proto);
if (serv != NULL)
port = serv->s_port;
else
/* Not in offerings, perhaps a number of? */
lport = strtol(provider,&errpos,0);
if ( (errpos[0] != 0 (lport < 1)
go back -1;
/* Invalid port cope with */
port = htons(lport);
return port;
Question nine. How Do I Properly Close A Socket?
Answer :
This question is normally asked by means of those who try near(), due to the fact they've visible that that is what they're purported to do, after which run netstat and notice that their socket is still lively. Yes, close() is an appropriate technique. To read about the TIME_WAIT country, and why it's far crucial, check with ``2.7 Please explain the TIME_WAIT kingdom.''.
WebSockets Interview Questions
Question 10. What Is The Difference Between Close() And Shutdown()?
Answer :
Generally the difference among close() and shutdown() is: near() closes the socket identity for the procedure however the connection continues to be opened if any other process shares this socket identity. The connection stays opened each for study and write, and now and again that is very essential. Shutdown() breaks the connection for all methods sharing the socket id. Those who try to study will detect EOF, and those who attempt to write will reseive SIGPIPE, possibly delayed at the same time as the kernel socket buffer can be filled. Additionally, shutdown() has a 2nd argument which denotes how to near the connection: zero way to disable further studying, 1 to disable writing and 2 disables both.
Socket.IO Tutorial
Question eleven. Explain The Time_wait State?
Answer :
Remember that TCP guarantees all statistics transmitted might be delivered, if in any respect feasible. When you shut a socket, the server goes into a TIME_WAIT nation, simply to be virtually really certain that every one the statistics has long gone through. When a socket is closed, both aspects agree with the aid of sending messages to every different that they will ship no more statistics. This, it regarded to me changed into good enough, and after the handshaking is performed, the socket must be closed. The hassle is two-fold. First, there may be no way to ensure that the ultimate ack turned into communicated correctly. Second, there may be "wandering duplicates" left at the net that need to be handled if they may be brought.
Socket Programming Interview Questions
Question 12. How Can I Put A Timeout On Connect()?
Answer :
First, create the socket and positioned it into non-blocking off mode, then call join().
There are three opportunities:
join succeeds: the connection has been effectively made (this normally handiest happens when connecting to the same machine)
join fails: apparent
join returns:-1/EINPROGRESS. The connection attempt has all started, but not yet completed.
If the relationship succeeds:
The socket will select() as writable (and also will pick out as readable if statistics arrives)
If the relationship fails:
The socket will pick out as readable and writable, however either a read or write will return the mistake code from the relationship strive. Also, you can use getsockopt(SO_ERROR) to get the error popularity - but be cautious; some structures return the mistake code inside the result parameter of getsockopt(), but others (incorrectly) reason the getsockopt name itself to fail with the stored fee as the mistake.
Networking Interview Questions
Question 13. Why Does The Sockets Buffer Fill Up Sooner Than Expected?
Answer :
In the conventional BSD socket implementation, sockets that are atomic such as UDP preserve received records in lists of mbufs. An mbuf is a set length buffer that is shared with the aid of numerous protocol stacks. When you place your receive buffer length, the protocol stack maintains music of how many bytes of mbuf space are on the receive buffer, not the range of actual bytes. This technique is used due to the fact the resource you are controlling is certainly what number of mbufs are used, no longer how many bytes are being held in the socket buffer. (A socket buffer isn't always truly a buffer in the conventional sense, however a list of mbufs).
For instance: Lets count on your UNIX has a small mbuf length of 256 bytes. If your get hold of socket buffer is ready to 4096, you may in shape 16 mbufs on the socket buffer. If you receive sixteen UDP packets which can be 10 bytes every, your socket buffer is full, and you've a hundred and sixty bytes of facts. If you obtain 16 UDP packets that are two hundred bytes every, your socket buffer is also complete, however includes 3200 bytes of facts. FIONREAD returns the whole range of bytes, no longer the wide variety of messages or bytes of mbufs. Because of this, it is not an awesome indicator of the way complete your obtain buffer is.
Additionaly, in case you get hold of UDP messages that are 260 bytes, you dissipate mbufs, and can most effective recieve 8 packets before your socket buffer is complete. In this situation, only 2080 bytes of the 4096 are held inside the socket buffer.
This instance is greatly simplified, and the actual socket buffer set of rules additionally takes into account some other parameters. Note that some older socket implementations use a 128 byte mbuf.
Unix/Linux Tutorial
Question 14. How Often Should I Re-transmit Un-acknowledged Messages?
Answer :
The handiest element to do is clearly pick out a reasonably small put off along with one 2nd and stick with it. The trouble is that this can congest your community with vain traffic if there's a problem on the lan or on the alternative device, and this introduced traffic may additionally simplest serve to make the problem worse.
Question 15. How Can I Be Sure That A Udp Message Is Received?
Answer :
You should layout your protocol to count on a affirmation lower back from the vacation spot while a message is acquired. Of route is the confirmation is despatched by using UDP, then it too is unreliable and might not make it back to the sender. If the sender does now not get affirmation lower back via a certain time, it'll need to re-transmit the message, perhaps greater than as soon as. Now the receiver has a hassle because it can have already received the message, so some way of dropping duplicates is needed. Most protocols use a message numbering scheme in order that the receiver can tell that it has already processed this message and go back any other confirmation. Confirmations will also should reference the message range so that the sender can tell which message is being confirmed.
Unix Inter-Process Communication (IPC) Interview Questions
Question sixteen. Of The Socket? Does Doing A Connect() Call Affect The Receive Behavior?
Answer :
Yes, in two approaches. First, simplest datagrams out of your "related peer" are returned. All others arriving at your port are not added to you.
But most importantly, a UDP socket must be connected to receive ICMP errors.
Unix makefile Tutorial
Question 17. When Should I Use Udp Instead Of Tcp?
Answer :
UDP is ideal for sending messages from one system to every other whilst the order is not crucial and also you don't need all the messages to get to the other device. This is why I've handiest used UDP once to jot down the example code for the faq. Usually TCP is a better answer. It saves you having to write code to make certain that messages make it to the favored destination, or to ensure the message ordering. Keep in thoughts that each extra line of code you add on your assignment in every other line that might include a doubtlessly high-priced malicious program.
If you locate that TCP is too slow for your needs you'll be able to get higher performance with UDP as long as you are willing to sacrifice message order and/or reliability.
UDP should be used to multicast messages to a couple of other system on the identical time. With TCP an application could should open separate connections to every of the destination machines and send the message as soon as to every target system. This limits your utility to handiest communicate with machines that it already is aware of about.
UNIX Memory Management Interview Questions
Question 18. How Can I Read Only One Character At A Time?
Answer :
This query is generally requested with the aid of people who are testing their server with telnet, and need it to system their keystrokes one individual at a time. The correct method is to use a psuedo terminal (pty). More on that in a minute.
You can have your server send a series of manage characters: 0xff 0xfb 0x01 0xff 0xfb 0x03 0xff 0xfd 0x0f3, which translates to IAC WILL ECHO IAC WILL SUPPRESS-GO-AHEAD IAC DO SUPPRESS-GO-AHEAD. For more records on what this means, test out std8, std28 and std29.
Roger additionally gave the following tips:
This code will suppress echo, so that you'll need to ship the characters the consumer types lower back to the customer if you want the consumer to peer them.
Carriage returns will be followed by means of a null individual, so you'll need to count on them.
If you get a 0xff, it will be accompanied by using more characters. These are telnet escapes.
Use of a pty might additionally be the perfect way to execute a baby manner and pass the i/o to a socket.
UNIX/XENIX Interview Questions
Question 19. What Is The Difference Between So_reuseaddr And So_reuseport?
Answer :
SO_REUSEADDR allows your server to bind to an address that's in a TIME_WAIT kingdom. It does not permit more than one server to bind to the identical cope with. It became cited that use of this flag can create a protection risk because any other server can bind to a the equal port, by using binding to a specific deal with as opposed to INADDR_ANY. The SO_REUSEPORT flag lets in more than one methods to bind to the same cope with furnished all of them use the SO_REUSEPORT choice.
This is a more recent flag that regarded within the 4.4BSD multicasting code (even though that code become from elsewhere, so I am no longer positive just who invented the brand new SO_REUSEPORT flag).
What this flag helps you to do is rebind a port that is already in use, but only if all users of the port specify the flag. I consider the rationale is for multicasting apps, due to the fact that in case you're running the same app on a number, all want to bind the identical port. But the flag can also have other uses. For example the following is from a submit in February.
SO_REUSEPORT is also useful for casting off the try-10-times-to-bind hack in ftpd's information connection setup ordinary. Without SO_REUSEPORT, only one ftpd thread can bind to TCP (lhost, lport, INADDR_ANY, 0) in guidance for connecting back to the consumer. Under conditions of heavy load, there are extra threads colliding here than the attempt-10-instances hack can accomodate. With SO_REUSEPORT, things work nicely and the hack will become needless.
I even have additionally heard that DEC OSF supports the flag. Also note that under four.4BSD, if you are binding a multicast address, then SO_REUSEADDR is condisered similar to SO_REUSEPORT (p. 731 of "TCP/IP Illustrated, Volume 2"). I assume below Solaris you simply update SO_REUSEPORT with SO_REUSEADDR.
From a later Stevens posting, with minor modifying:
Basically SO_REUSEPORT is a BSD'ism that arose whilst multicasting changed into added, even idea it became now not used in the original Steve Deering code. I trust some BSD-derived structures may also encompass it (OSF, now Digital Unix, perhaps?). SO_REUSEPORT helps you to bind the same address *and* port, but best if all the binders have distinctive it. But whilst binding a multicast deal with (its essential use), SO_REUSEADDR is taken into consideration identical to SO_REUSEPORT (p. 731, "TCP/IP Illustrated, Volume 2"). So for portability of multicasting packages I continually use SO_REUSEADDR.
Question 20. How Do I Get My Server To Find Out The Clients Address / Host- Name?
Answer :
After receive()ing a connection, use getpeername() to get the address of the purchaser. The purchaser's address is of course, additionally again at the take delivery of(), but it's far essential to initialise the address-length parameter earlier than the accept name for this may work. Int t;
int len;
struct sockaddr_in sin;
struct hostent *host;
len = sizeof sin;
if (getpeername(t, (struct sockaddr *)
&sin, &len) < 0)
perror("getpeername");
else
if ((host = gethostbyaddr((char *)
&sin.Sin_addr,sizeof sin.Sin_addr,
AF_INET)) == NULL)
perror("gethostbyaddr");
else printf("remote host is '%s'n",
host->h_name);
UNIX Process Management Interview Questions
Question 21. What Exactly Does So_keepalive Do?
Answer :
The SO_KEEPALIVE choice causes a packet (known as a 'keepalive probe') to be sent to the far flung gadget if a long term (by default, greater than 2 hours) passes and not using a other information being sent or received. This packet is designed to initiate an ACK response from the peer. This enables detection of a peer which has emerge as unreachable (e.G. Powered off or disconnected from the net).
Note that the parent of two hours comes from RFC1122, "Requirements for Internet Hosts". The specific fee need to be configurable, but I've regularly discovered this to be hard. The only implementation I recognize of that allows the keepalive c programming language to be set consistent with-connection is SVR4.2.
Question 22. What Exactly Does So_reuseaddr Do?
Answer :
This socket alternative tells the kernel that although this port is busy (in the TIME_WAIT kingdom), go ahead and reuse it anyway. If it's miles busy, but with another nation, you will nevertheless get an address already in use blunders. It is beneficial if your server has been shut down, after which restarted right away even as sockets are nonetheless lively on its port. You must be conscious that if any unexpected statistics comes in, it is able to confuse your server, but at the same time as this is possible, it isn't possibly.
It has been talked about that "A socket is a 5 tuple (proto, local addr, local port, remote addr, far flung port). SO_REUSEADDR simply says that you may reuse local addresses. The five tuple still have to be particular!" through Michael Hunter (mphunter@qnx.Com). This is genuine, and that is why it's miles not possible that sudden facts will ever be seen by means of your server. The danger is that one of these 5 tuple is still floating around at the internet, and whilst it is bouncing round, a new connection from the equal client, at the identical system, occurs to get the equal far off port. This is explained by Richard Stevens in ``2.7 Please give an explanation for the TIME_WAIT kingdom.''.
Question 23. How Can I Make My Server A Daemon?
Answer :
There are methods you could take here. The first is to use inetd to do all the difficult give you the results you want. The 2d is to do all of the difficult work your self. If you operate inetd, you clearly use stdin, stdout, or stderr for your socket. (These three are all created with dup() from the actual socket) You can use these as you will a socket to your code. The inetd procedure may even close the socket for you when you are finished.
#encompass <stdio.H>
#include <stdlib.H>
#include <ctype.H>
#consist of <unistd.H>
#include <fcntl.H>
#include <signal.H>
#encompass <sys/wait.H>
/* Global variables */
unstable sig_atomic_t keep_going = 1;
/* controls software termination */
/* Function prototypes: */
void termination_handler (int signum);
/* easy up before termination */
int
most important (void)
...
If (chdir (HOME_DIR))
/* alternate to directory containing records
documents */
fprintf (stderr, "`%s': ", HOME_DIR);
perror (NULL);
exit (1);
/* Become a daemon: */
transfer (fork ())
case -1:
/* can not fork */
perror ("fork()");
go out (3);
case 0:
/* toddler, technique becomes a daemon: */
close (STDIN_FILENO);
close (STDOUT_FILENO);
near (STDERR_FILENO);
if (setsid () == -1)
/* request a new session (activity manipulate) */
exit (four);
break;
default:
/* discern returns to calling method: */
return zero;
/* Establish signal handler to
clean up earlier than termination: */
if (sign (SIGTERM, termination_handler)
== SIG_IGN)
sign (SIGTERM, SIG_IGN);
signal (SIGINT, SIG_IGN);
sign (SIGHUP, SIG_IGN);
/* Main software loop */
whilst (keep_going)
...
Go back zero;
void
termination_handler (int signum)
keep_going = 0;
sign (signum, termination_handler);
Advanced C++ Interview Questions
Question 24. How Come I Get Address Already In Use From Bind()?
Answer :
You get this whilst the address is already in use. (Oh, you figured that a great deal out?) The maximum commonplace cause for this is which you have stopped your server, and then re-started out it proper away. The sockets that had been utilized by the first incarnation of the server are still active. This is further explained in ``2.7 Please provide an explanation for the TIME_WAIT kingdom.'', and ``2.Five How do I properly close a socket''.
Java-Multithreading Interview Questions
Question 25. Why Do I Get Connection Refused When The Server Is Not Running?
Answer :
The connect() call will most effective block while it's miles waiting to set up a connection. When there's no server ready at the opposite end, it gets notified that the relationship cannot be mounted, and gives up with the mistake message you see. This is a good issue, due to the fact if it were not the case customers would possibly look forward to ever for a provider which simply doesn't exist. Users could think that they had been most effective looking forward to the connection to be established, and then after some time give up, muttering something about crummy software program below their breath.
Question 26. How Can I Set The Timeout For The Connect() System Call?
Answer :
Normally you cannot trade this. Solaris does permit you to do this, on a in line with-kernel foundation with the ndd tcp_ip_abort_cinterval parameter.
The easiest way to shorten the connect time is with an alarm() around the decision to connect(). A more difficult way is to apply pick(), after setting the socket nonblocking. Also note that you can only shorten the connect time, there is generally no manner to lengthen it.
First, create the socket and positioned it into non-blocking off mode, then call connect().
There are 3 possibilities:
connect succeeds: the relationship has been correctly made (this commonly simplest takes place when connecting to the same machine)
join fails: obvious
connect returns: -1/EINPROGRESS. The connection try has begun, however not but finished.
If the connection succeeds:
The socket will choose() as writable (and will also pick as readable if facts arrives)
If the connection fails:
The socket will choose as readable and writable, but either a examine or write will go back the error code from the relationship strive. Also, you can use getsockopt(SO_ERROR) to get the error status - however be careful; some structures return the error code inside the result parameter of getsockopt, however others (incorrectly) purpose the getsockopt call itself to fail with the stored value as the mistake.
Basic C Interview Questions
Question 27. Why Does Connect() Succeed Even Before My Server Did An Accept()?
Answer :
Once you've got carried out a listen() name to your socket, the kernel is primed to just accept connections on it. The ordinary UNIX implementation of this works by means of right now completing the SYN handshake for any incoming valid SYN segments (connection attempts), growing the socket for the new connection, and maintaining this new socket on an internal queue ready for the take delivery of() call. So the socket is fully open before the receive is finished.
The other element in this is the 'backlog' parameter for pay attention(); that defines how many of those finished connections may be queued at one time. If the specified range is handed, then new incoming connects are genuinely disregarded (which reasons them to be retried).
WebSockets Interview Questions
Question 28. How Do I Convert A String Into An Internet Address?
Answer :
If you are studying a bunch's deal with from the command line, you can now not recognise when you have an aaa.Bbb.Ccc.Ddd style address, or a bunch.Area.Com fashion deal with. What I do with these, is first attempt to use it as a aaa.Bbb.Ccc.Ddd type address, and if that fails, then do a call lookup on it. Here is an example.
/* Converts ascii text to in_addr struct.
/* NULL is lower back if the
deal with can not be determined. */
struct in_addr *atoaddr(char *cope with)
struct hostent *host;
static struct in_addr saddr;
/* First strive it as aaa.Bbb.Ccc.Ddd. */
saddr.S_addr = inet_addr(cope with);
if (saddr.S_addr != -1)
go back &saddr;
host = gethostbyname(deal with);
if (host != NULL)
go back (struct in_addr *) *host->h_addr_list;
go back NULL;
Question 29. What Are Socket Exceptions? What Is Out-of-band Data?
Answer :
Unlike exceptions in C++, socket exceptions do no longer imply that an error has occured. Socket exceptions commonly check with the notification that out-of-band statistics has arrived. Out-of-band information (known as "pressing information" in TCP) appears to the software like a separate stream of information from the primary information movement. This can be beneficial for isolating exceptional forms of information. Note that just due to the fact it's miles referred to as "urgent records" does not suggest that it will be introduced any quicker, or with higher priorety than information inside the in-band records circulate. Also beware that not like the principle information circulation, the out-of-bound facts may be lost if your application cannot preserve up with it.
Unix/Linux Interview Questions
Question 30. Why Do I Keep Getting Eintr From The Socket Calls?
Answer :
This is not simply a lot an error as an exit circumstance. It means that the decision become interrupted by using a sign. Any call that would block have to be wrapped in a loop that checkes for EINTR, as is performed in the example code .
Question 31. Is There Any Advantage To Handling The Signal, Rather Than Just Ignoring It And Checking For The Epipe Error? Are There Any Useful Parameters Passed To The Signal Catching Function?
Answer :
See that send()/write() can generate SIGPIPE. Is there any benefit to managing the sign, in preference to simply ignoring it and checking for the EPIPE error. Are there any beneficial parameters exceeded to the sign catching feature.
In popular, the simplest parameter passed to a sign handler is the signal variety that induced it to be invoked. Some systems have optional extra parameters, however they are little need to you in this case.
My recommendation is to simply forget about SIGPIPE as you suggest. That's what I do in just about all of my socket code; errno values are simpler to handle than alerts (in fact, the first revision of the FAQ failed to mention SIGPIPE in that context; I'd got so used to ignoring it...)
There is one state of affairs wherein you need to now not ignore SIGPIPE; in case you are going to exec() every other application with stdout redirected to a socket. In this case it might be wise to set SIGPIPE to SIG_DFL earlier than doing the exec().
Question 32. How Do I Send [this] Over A Socket?
Answer :
Anything apart from unmarried bytes of statistics will in all likelihood get mangled unless you are taking care. For integer values you can use htons() and friends, and strings are definitely only a bunch of unmarried bytes, so the ones need to be OK. Be cautious no longer to send a pointer to a string even though, since the pointer might be meaningless on another system. If you want to send a struct, you should write sendthisstruct() and readthisstruct() functions for it that do all of the work of taking the structure aside on one facet, and placing it returned together on the opposite. If you want to ship floats, you may have a number of work beforehand of you. You must read RFC 1014 which is about portable methods of getting statistics from one system to any other (thanks to Andrew Gabriel for pointing this out).
Unix Production Support Interview Questions
Question 33. How Come Select Says There Is Data, But Read Returns Zero?
Answer :
The records that reasons pick out to go back is the EOF due to the fact the alternative aspect has closed the relationship. This causes study to return 0.
Socket Programming Interview Questions
Question 34. How Can I Force A Socket To Send The Data In Its Buffer?
Answer :
You can't force it. Period. TCP makes up its own mind as to when it could ship data. Now, generally when you call write() on a TCP socket, TCP will indeed send a segment, but there's no guarantee and no manner to pressure this. There are lots of reasons why TCP will not send a segment: a closed window and the Nagle set of rules are things to return straight away to thoughts.
Setting this most effective disables one of the many exams, the Nagle algorithm. But if the authentic poster's hassle is that this, then placing this socket alternative will help.
A quick look at tcp_output() indicates around 11 tests TCP has to make as to whether to ship a segment or no longer.
As you've got surmised, I've never had any hassle with disabling Nagle's set of rules. Its basically a buffering approach; there may be a hard and fast overhead for all packets, regardless of how small. Hence, Nagle's set of rules collects small packets together (no greater than .2sec postpone) and thereby reduces the amount of overhead bytes being transferred. This method works well for rcp, for example: the .2 second delay is not humanly major, and multiple users have their small packets extra correctly transferred. Helps in college settings where maximum folks the usage of the community are the use of fashionable equipment including rcp and ftp, and packages such as telnet may also use it, too.
However, Nagle's algorithm is natural havoc for actual-time manage and not an awful lot higher for keystroke interactive programs (manage-C, anybody?). It has seemed to me that the forms of new programs the usage of sockets that human beings write commonly do have problems with small packet delays. One manner to pass Nagle's set of rules selectively is to apply "out-of-band" messaging, but that is limited in its content material and has other effects (along with a lack of sequentiality) (via the way, out-of- band is regularly used for that ctrl-C, too).
So to sum it all up, if you are having trouble and want to flush the socket, setting the TCP_NODELAY choice will commonly remedy the hassle. If it would not, you may should use out-of-band messaging, however consistent with Andrew, "out-of-band information has its own problems, and I do not think it really works nicely as a option to buffering delays (haven't attempted it although). It isn't 'expedited data' in the sense that exists in a few other protocols; it is transmitted in-stream, however with a pointer to signify where it's miles."
Question 35. What Are The Pros/cons Of Select(), Non-blocking off I/o And Sigio?
Answer :
Using non-blockading I/O method that you need to ballot sockets to peer if there's information to be read from them. Polling have to typically be avoided since it uses extra CPU time than other strategies.
Using SIGIO lets in your application to do what it does and feature the operating gadget inform it (with a sign) that there is information waiting for it on a socket. The only drawback to this soltion is that it could be perplexing, and if you are managing a couple of sockets you'll need to do a pick out() besides to discover which one(s) is ready to be read.
Using select() is remarkable if your application has to just accept facts from a couple of socket at a time because it's going to block till anyone of some of sockets is prepared with records. One different benefit to pick out() is that you could set a time-out fee and then manipulate might be returned to you whether or not any of the sockets have data for you or not.
Question 36. Why Does It Take So Long To Detect That The Peer Died?
Answer :
Because with the aid of default, no packets are sent at the TCP connection until there's records to send or well known.
So, in case you are really anticipating information from the peer, there's no way to tell if the peer has silently long past away, or simply isn't ready to send any extra information yet. This may be a trouble (mainly if the peer is a PC, and the consumer just hits the Big Switch...).
One solution is to use the SO_KEEPALIVE choice. This alternative permits periodic probing of the relationship to make certain that the peer remains present. BE WARNED: the default timeout for this option is AT LEAST 2 HOURS. This timeout can frequently be altered (in a system-established fashion) however no longer usually on a in step with-connection basis (AFAIK).
RFC1122 specifies that this timeout (if it exists) must be configurable. On most people of Unix editions, this configuration can also handiest be finished globally, affecting all TCP connections that have keepalive enabled. The technique of changing the value, furthermore, is frequently hard and/or poorly documented, and in any case is exclusive for pretty much each version in existence.
If you must exchange the fee, look for something similar to tcp_keepidle on your kernel configuration or network alternatives configuration.
If you're sending to the peer, though, you have got a few better ensures; given that sending data implies receiving ACKs from the peer, then you will know after the retransmit timeout whether or not the peer continues to be alive. But the retransmit timeout is designed to allow for numerous contingencies, with the aim that TCP connections are not dropped really due to minor community upsets. So you have to nevertheless assume a postpone of numerous mins before getting notification of the failure.
The method taken by using maximum utility protocols currently in use at the Internet (e.G. FTP, SMTP and many others.) is to enforce read timeouts at the server quit; the server really offers up at the patron if no requests are acquired in a given term (frequently of the order of 15 mins).
Protocols in which the relationship is maintained even if idle for long intervals have alternatives:
use SO_KEEPALIVE
use a higher-level keepalive mechanism (along with sending a null request to the server every so often).
Unix Inter-Process Communication (IPC) Interview Questions
Question 37. Why Do I Get Eproto From Read()?
Answer :
EPROTO means that the protocol encountered an unrecoverable mistakes for that endpoint. EPROTO is one of these catch-all mistakes codes used by STREAMS-primarily based drivers when a better code isn't always available.
Not quite to do with EPROTO from examine(), however I determined out once that on a few STREAMS-based totally implementations, EPROTO could be returned through receive() if the incoming connection turned into reset earlier than the accept completes.
On some different implementations, receive regarded to be capable of blockading if this occured. This is critical, on account that if pick out() said the listening socket become readable, then you definately might typically assume now not to dam inside the be given() call. The restore is, of course, to set nonblocking mode on the listening socket in case you are going to use choose() on it.
Question 38. Where Can A Get A Library For Programming Sockets?
Answer :
There is the Simple Sockets Library by Charles E. Campbell, Jr. PhD. And Terry McRoberts. The file is known as ssl.Tar.Gz, and you may download it from this faq's home page. For c++ there is the Socket++ library that is on ftp://ftp.Virginia.Edu/pub/socket++-1.10.Tar.Gz. There is likewise C++ Wrappers. The document is known as ftp://ftp.Huji.Ac.Il/pub/languages/C++/. Thanks to Bill McKinnon for monitoring it down for me! From http://www.Cs.Wustl.Edu/~schmidt you have to be able to find the ACE toolkit. PING Software Group has a few libraries that encompass a sockets interface among different matters. You can locate them at http://love.Geology.Yale.Edu/~markl/ping.
Question 39. Whats The Difference Between Select() And Poll()?
Answer :
The primary distinction is that pick()'s fd_set is a chunk mask and therefore has a few constant length. It could be viable for the kernel to not restriction this size while the kernel is compiled, allowing the utility to define FD_SETSIZE to some thing it desires (because the comments within the machine header suggest these days) but it takes more paintings. Four.4BSD's kernel and the Solaris library feature each have this restrict. But I see that BSD/OS 2.1 has now been coded to avoid this restrict, so it's conceivable, only a small count number of programming. :-) Someone need to report a Solaris computer virus record on this, and spot if it ever receives fixed.
With poll(), however, the consumer should allocate an array of pollfd systems, and skip the range of entries in this array, so there is no fundamental restrict. As Casper notes, fewer structures have poll() than pick out, so the latter is more transportable. Also, with original implementations (SVR3) you couldn't set the descriptor to -1 to tell the kernel to ignore an access in the pollfd structure, which made it tough to dispose of entries from the array; SVR4 receives around this. Personally, I constantly use select() and seldom poll(), because I port my code to BSD environments too. Someone could write an implementation of ballot () that makes use of choose(), for these environments, however I've in no way visible one. Both pick() and poll() are being standardized by means of POSIX 1003.1g.
Question forty. How Do I Use Tcp_no Delay?
Answer :
First off, be sure you really need to apply it in the first region. It will disable the Nagle set of rules (see ``2.11 How can I pressure a socket to send the records in its buffer?''), as a way to purpose community site visitors to boom, with smaller than wanted packets wasting bandwidth. Also, from what I have been capable to inform, the speed increase is very small, so that you ought to in all likelihood do it with out TCP_NODELAY first, and only flip it on if there may be a problem.
Here is a code instance,
with a warning approximately the usage of it
int flag = 1;
int end result = setsockopt(sock,
/* socket affected */
IPPROTO_TCP,
/* set option at TCP stage */
TCP_NODELAY,
/* call of option */
(char *) &flag,
/* the forged is ancient cruft */
sizeof(int));
/* length of alternative price */
if (end result < zero)
... Handle the mistake ...
TCP_NODELAY is for a selected reason; to disable the Nagle buffering algorithm. It need to simplest be set for packages that ship common small bursts of information with out getting a right away response, where well timed shipping of information is needed (the canonical instance is mouse actions).
UNIX Memory Management Interview Questions
Question 41. What Is The Difference Between Read() And Recv()?
Answer :
examine() is equivalent to recv() with a flags parameter of zero. Other values for the flags parameter alternate the behaviour of recv(). Similarly, write() is equivalent to send() with flags == zero.
It is not going that ship()/recv() might be dropped; possibly someone with a copy of the POSIX drafts for socket calls can check...
Portability be aware: non-unix systems won't permit read()/write() on sockets, however recv()/ship() are normally adequate. This is proper on Windows and OS/2, as an example.
Question forty two. After The Chroot(), Calls To Socket() Are Failing. Why?
Answer :
On structures wherein sockets are implemented on pinnacle of Streams (e.G. All SysV-based structures, presumably along with Solaris), the socket() feature will without a doubt be opening positive unique files in /dev. You will need to create a /dev listing below your fake root and populate it with the desired tool nodes (most effective).
Your gadget documentation may also or won't specify precisely which tool nodes are required; counseled checking the person page for ftpd, which ought to listing the files you need to copy and gadgets you need to create within the chroot'd surroundings.)
A less-apparent difficulty with chroot() is in case you call syslog(), as many daemons do; syslog() opens (relying at the machine) both a UDP socket, a FIFO or a Unix-area socket. So in case you use it after a chroot() name, ensure which you call openlog() earlier than the chroot.
UNIX Process Management Interview Questions
Question forty three. When Will My Application Receive Sigpipe?
Answer :
Very easy: with TCP you get SIGPIPE if your cease of the connection has acquired an RST from the other cease. What this also method is that if you have been using choose rather than write, the select might have indicated the socket as being readable, because the RST is there so one can read (read will go back an errors with errno set to ECONNRESET).
Basically an RST is TCP's response to a few packet that it would not assume and has no other way of dealing with. A commonplace case is while the peer closes the relationship (sending you a FIN) however you forget about it because you're writing and not analyzing. (You need to be the use of pick out.) So you write to a connection that has been closed by using the alternative stop and the alternative end's TCP responds with an RST.
Question forty four. How Can I Find The Full Hostname (fqdn) Of The System I Am Running On?
Answer :
Some systems set the hostname to the FQDN and others set it to simply the unqualified host name. I recognise the modern-day BIND FAQ recommends the FQDN, but most Solaris systems, as an instance, generally tend to apply most effective the unqualified host call.
Regardless, the manner around that is to first get the host's call (perhaps an FQDN, possibly unaualified). Most systems assist the Posix manner to try this the use of uname(), but older BSD structures only provide gethostname(). Call gethostbyname() to find your IP deal with. Then take the IP address and call gethostbyaddr(). The h_name member of the hostent must then be your FQDN.
Question forty five. How Can My Client Work Through A Firewall/proxy Server?
Answer :
If you are walking via separate proxies for every service, you shouldn't need to do whatever. If you're operating thru socked, you may want to "sissify" your application.
Question 46. Why Do I Sometimes Lose A Servers Address When Using More Than One Server?
Answer :
Take a cautious observe struct hostent. Notice that almost the whole thing in it's far a pointer? All those recommendations will talk over with statically allocated statistics.
For example, if you do:
struct hostent *host = gethostbyname(hostname);
then (as you must understand) a subsequent call to gethostbyname() will overwrite the shape pointed to by using 'host'.
But in case you do:
struct hostent myhost;
struct hostent *hostptr = gethostbyname(hostname);
if (hostptr) myhost = *host;
to make a copy of the hostent earlier than it receives overwritten, then it nonetheless receives clobbered by way of a subsequent name to gethostbyname(), due to the fact although myhost won't get overwritten, all the information it is pointing to may be.
You can get spherical this with the aid of doing a proper 'deep copy' of the hostent shape, but that is tedious. My advice would be to extract the wanted fields of the hostent and store them to your very own way.
It might be excellent in case you point out MT safe libraries provide complimentary features for multithreaded programming. On the solaris gadget I'm typing at, we've got gethostbyname and gethostbyname_r (_r for reentrant). The fundamental distinction is, you provide the garage for the hostent struct so you usually have a local replica and not just a pointer to the static reproduction.
Question 47. System Choose One For Me On The Connect() Call? Should I Bind() A Port Number In My Client Program, Or Let The?
Answer :
Let the machine pick out your patron's port variety:
The exception to this, is if the server has been written to be picky approximately what client ports it's going to permit connections from. Rlogind and rshd are the classic examples. This is generally a part of a Unix-precise (and as a substitute weak) authentication scheme; the reason is that the server lets in connections handiest from procedures with root privilege. (The weakness in the scheme is that many O/Ss (e.G. MS-DOS) allow anyone to bind any port.)
The rresvport() habitual exists to help out customers which might be using this scheme. It basically does the equal of socket() + bind(), selecting a port wide variety within the range 512..1023.
If the server isn't always fussy approximately the customer's port range, then don't attempt to assign it your self within the purchaser, simply permit join() pick it for you.
If, in a customer, you operate the naive scheme of starting at a set port variety and calling bind() on consecutive values till it really works, then you definately purchase yourself an entire lot of trouble:
The hassle is if the server give up of your connection does an energetic close. (E.G. Consumer sends 'QUIT' command to server, server responds with the aid of last the connection). That leaves the consumer stop of the relationship in CLOSED country, and the server lead to TIME_WAIT nation. So after the patron exits, there may be no trace of the relationship at the customer end.
Now run the consumer once more. It will pick the identical port wide variety, on account that as far as it can see, it's loose. But as quickly because it calls join(), the server finds that you are trying to copy an current connection (even though one in TIME_WAIT). It is perfectly entitled to refuse to do this, so that you get, I suspect, ECONNREFUSED from connect(). (Some structures might also sometimes allow the connection anyway, but you can't depend on it.)
This hassle is specifically risky as it doesn't show up until the consumer and server are on exceptional machines. (If they're the same system, then the patron won't pick out the identical port quantity as
before). So you can get bitten nicely into the improvement cycle (if you do what I suspect most of the people do, and test purchaser & server on the same box initially).
Even in case your protocol has the consumer final first, there are nonetheless approaches to supply this hassle (e.G. Kill the server).
Question 48. Over The Socket? Is There A Way To Have A Dynamic Buffer? What Does One Do When One Does Not Know How Much Information Is Coming?
Answer :
When the scale of the incoming statistics is unknown, you can either make the size of the buffer as large as the largest viable (or probably) buffer, or you can re-length the buffer at the fly at some point of your read. When you malloc() a large buffer, most (if now not all) varients of unix will best allocate deal with area, however now not bodily pages of ram. As increasingly of the buffer is used, the kernel allocates bodily reminiscence. This way that malloc'ing a huge buffer will not waste resources until that reminiscence is used, and so it is flawlessly desirable to invite for a meg of ram while you expect only some K.
On the other hand, a more stylish answer that does not depend on the internal workings of the kernel is to use realloc() to amplify the buffer as required in say 4K chunks (considering 4K is the size of a page of ram on most structures). I can also add something like this to sockhelp.C in the example code in the future.
Question forty nine. Why Do Not My Sockets Close?
Answer :
When you problem the close() machine name, you're closing your interface to the socket, no longer the socket itself. It is as much as the kernel to close the socket. Sometimes, for really technical reasons, the socket is stored alive for a couple of minutes after you close it. It is ordinary, as an instance for the socket to go into a TIME_WAIT country, at the server facet, for a couple of minutes. People have suggested tiers from 20 seconds to four mins to me. The reputable popular says that it need to be 4 mins. On my Linux gadget it's far approximately 2 mins. This is defined in first rate element in ``2.7 Please explain the TIME_WAIT kingdom.''.
Question 50. How Can I Listen On More Than One Port At A Time?
Answer :
The first-class way to do that is with the choose() name. This tells the kernel to assist you to understand whilst a socket is available to be used. You may have one system do i/o with more than one sockets with this name.
If you want to watch for a join on sockets four, 6 and 10 you would possibly execute the subsequent code snippet:
fd_set socklist;
FD_ZERO(&socklist); /* Always clean the shape first. */
FD_SET(4, &socklist);
FD_SET(6, &socklist);
FD_SET(10, &socklist);
if (choose(11, NULL, &socklist, NULL, NULL) < 0)
perror("pick out");
The kernel will notify us as quickly as a record descriptor that is much less than eleven (the primary parameter to pick out()), and is a member of our

