EzDevInfo.com

sockets interview questions

Top sockets frequently asked interview questions

What is the difference between a port and a socket?

This was a question raised by one of the software engineers in my organisation. I'm interested in the broadest definition.


Source: (StackOverflow)

What does "connection reset by peer" mean?

What is the meaning of the "connection reset by peer" error on a TCP connection? Is it a fatal error or just a notification?


Source: (StackOverflow)

Advertisements

TypeError: 'module' object is not callable

File "C:\Users\Administrator\Documents\Mibot\oops\blinkserv.py", line 82, in __init__
    self.serv = socket(AF_INET,SOCK_STREAM)
TypeError: 'module' object is not callable

Why am I getting this error? I'm confused.

What do you need to know to answer my question?


Source: (StackOverflow)

centos: Another MySQL daemon already running with the same unix socket

I have a strange error when starting mysqld service:

Another MySQL daemon already running with the same unix socket.

I've tried to list running services and stopping them but the same error happens when starting mysqld service.

I can try to remove the mysqld and reinstall it but will this remove the database too?


Source: (StackOverflow)

What's causing my java.net.SocketException: Connection reset?

We are seeing frequent java.net.SocketException: Connection reset errors in our logs for a component that calls a third party Web service that sends SMS messages.

Our application is written in Java and is sat on top of Tomcat 5.5. It was written by contractors who are no longer with us. The current team has no real Java expertise, and we're unsure as to where the Connection reset error is actually coming from, and how to go about debugging.

The issue appears to be completely intermittent, and unrelated to the messages we are attempting to send.

Any suggestions on what the typical causes of this exception might be, and how we might proceed, are welcome.

The whole call stack is included below for completeness.

(com.companyname.mtix.sms is our component)

java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(SocketInputStream.java:168)
    at java.io.BufferedInputStream.fill(BufferedInputStream.java:218)
    at java.io.BufferedInputStream.read(BufferedInputStream.java:235)
    at org.apache.commons.httpclient.HttpParser.readRawLine(HttpParser.java:77)
    at org.apache.commons.httpclient.HttpParser.readLine(HttpParser.java:105)
    at org.apache.commons.httpclient.HttpConnection.readLine(HttpConnection.java:1115)
    at org.apache.commons.httpclient.HttpMethodBase.readStatusLine(HttpMethodBase.java:1832)
    at org.apache.commons.httpclient.HttpMethodBase.readResponse(HttpMethodBase.java:1590)
    at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:995)
    at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:397)
    at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:170)
    at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:396)
    at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:324)
    at com.companyname.mtix.sms.services.impl.message.SendTextMessage.sendTextMessage(SendTextMessage.java:127)
    at com.companyname.mtix.sms.services.MessageServiceImpl.sendTextMessage(MessageServiceImpl.java:125)
    at com.companyname.mtix.sms.services.remote.MessageServiceRemoteImpl.sendTextMessage(MessageServiceRemoteImpl.java:43)
    at sun.reflect.GeneratedMethodAccessor203.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:585)
    at org.apache.axis.providers.java.RPCProvider.invokeMethod(RPCProvider.java:397)
    at org.apache.axis.providers.java.RPCProvider.processMessage(RPCProvider.java:186)
    at org.apache.axis.providers.java.JavaProvider.invoke(JavaProvider.java:323)
    at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32)
    at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:118)
    at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83)
    at org.apache.axis.handlers.soap.SOAPService.invoke(SOAPService.java:453)
    at org.apache.axis.server.AxisServer.invoke(AxisServer.java:281)
    at org.apache.axis.transport.http.AxisServlet.doPost(AxisServlet.java:699)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
    at org.apache.axis.transport.http.AxisServletBase.service(AxisServletBase.java:327)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
    at com.companyname.mtix.sms.http.filters.NoCacheFilter.doFilter(NoCacheFilter.java:63)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
    at com.companyname.mtix.sms.http.filters.MessageFilter.doFilter(MessageFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:61)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:77)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
    at org.ajaxanywhere.AAFilter.doFilter(AAFilter.java:46)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:541)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:869)
    at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:664)
    at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
    at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
    at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
    at java.lang.Thread.run(Thread.java:595)

Edit

The line of our code on which the exception gets thrown from is the last line in the code snippet below.

String aggregatorResponse = null;
HttpClient httpClient = prepareHttpClient( username, password );
PostMethod postMethod = preparePostMethod( textUrl );

try {
  SybaseTextMessageBuilder builder = new SybaseTextMessageBuilder();
  URL notifyUrl = buildNotificationUrl( textMessage, codeSetManager );
  String smsRequestDocument = builder.buildTextMessage( textMessage, notifyUrl );
  LOG.debug( "Sybase MT document created as: \n" + smsRequestDocument );

  postMethod.setRequestEntity( new StringRequestEntity( smsRequestDocument ) );
  LOG.debug( "commiting SMS to aggregator: " + textMessage.toString() );
  int httpStatus = httpClient.executeMethod( postMethod );

Source: (StackOverflow)

How to detect a remote side socket close?

How do you detect if Socket#close() has been called on a socket on the remote side?


Source: (StackOverflow)

Socket options SO_REUSEADDR and SO_REUSEPORT, how do they differ? Do they mean the same across all major operating systems?

The man pages and programmer documentations for the socket options SO_REUSEADDR and SO_REUSEPORT are different for different operating systems and often highly confusing. Some operating systems don't even have the option SO_REUSEPORT. The WEB is full of contradicting information regarding this subject and often you can find information that is only true for one socket implementation of a specific operating system, which may not even be explicitly mentioned in the text.

So how exactly is SO_REUSEADDR different than SO_REUSEPORT?

Are systems without SO_REUSEPORT more limited?

And what exactly is the expected behavior if I use either one on different operating systems?


Source: (StackOverflow)

How much overhead does SSL impose?

I know there's no single hard-and-fast answer, but is there a generic order-of-magnitude estimate approximation for the encryption overhead of SSL versus unencrypted socket communication? I'm talking only about the comm processing and wire time, not counting application-level processing.

Update

There is a question about HTTPS versus HTTP, but I'm interested in looking lower in the stack.

(I replaced the phrase "order of magnitude" to avoid confusion; I was using it as informal jargon rather than in the formal CompSci sense. Of course if I had meant it formally, as a true geek I would have been thinking binary rather than decimal! ;-)

Update

Per request in comment, assume we're talking about good-sized messages (range of 1k-10k) over persistent connections. So connection set-up and packet overhead are not significant issues.


Source: (StackOverflow)

What is the largest Safe UDP Packet Size on the Internet

I've read a number of articles about UDP packet sizes but have been unable to come to a conclusion on whats correct.

A number of services restrict the largest UDP packet to 512 bytes (like dns)

Given the minimum MTU on the internet is 576 , and the size of the IPv4 header is 20 bytes, and the UDP header 8 bytes. This leaves 548 bytes available for user data

Would I be able to use packets up to the size of 548 without packet fragmentation? Or is there something the creators of DNS knew about, and that why they restricted it to 512 bytes.

Could I even go higher than 548 bytes safely?


Source: (StackOverflow)

Official reasons for "Software caused connection abort: socket write error"

Given this stack trace snippet

Caused by: java.net.SocketException: Software caused connection abort: socket write error
 at java.net.SocketOutputStream.socketWrite0(Native Method)

I tried to answer the following questions:

  1. What code is throwing this exception? (JVM?/Tomcat?/My code?)
  2. What causes this exception to be thrown?

Regarding #1:

Sun's JVM source doesn't contain this exact message, but I think the text Software caused connection abort: socket write error is from the native implementation of SocketOutputStream:

private native void socketWrite0(FileDescriptor fd, byte[] b, int off,
                 int len) throws IOException;

Regarding #2

My guess is that it is caused when the client has terminated the connection, before getting the full response (e.g. sent a request, but before getting the full response, it got closed / terminated / offline)

Questions:

  1. Are the above assumptions correct (#1 and #2)?
  2. Can this be diffrentiated from the situation: "could not write to the client, due to a network error on the server side"? or would that render the same error message?
  3. And most important: Is there an official document (e.g from Sun) stating the above?

I need to have a proof that this stack trace is the socket client's "fault", and there is nothing that the server could have done to avoid it. (except catching the exception, or using a non Sun JVM SocketOutputStream, though both don't really avoid the fact the client has terminated)


Source: (StackOverflow)

Getting the IP address of the current machine using Java

I am trying to develop a system where there are different nodes that are run on different system or on different ports on the same system. Now all the nodes create a Socket with a target IP as the IP of a special node known as a bootstrapping node. The nodes then create their own ServerSocket and start listening for connections. The bootstrapping node maintains a list of Nodes and returns them on being quired. Now what I need is the node must register its IP to the bootstrapping node. I tried using cli.getInetAddress() once the client connects to the ServerSocket of bootstrapping node but that didn't work.

  1. I need the client to register its PPP IP if available;
  2. Otherwise the LAN IP if available;
  3. Otherwise it must register 127.0.0.1 assuming its the same computer.

Please help me with this.

EDIT

using the code:

System.out.println(Inet4Address.getLocalHost().getHostAddress());

or

System.out.println(InetAddress.getLocalHost().getHostAddress());

My PPP Connection IP address is: 117.204.44.192 but the above returns me 192.168.1.2

EDIT2

I am using the following code:

Enumeration e = NetworkInterface.getNetworkInterfaces();
while(e.hasMoreElements())
{
    NetworkInterface n = (NetworkInterface) e.nextElement();
    Enumeration ee = n.getInetAddresses();
    while (ee.hasMoreElements())
    {
        InetAddress i = (InetAddress) ee.nextElement();
        System.out.println(i.getHostAddress());
    }
}

I am able to get all the IP addresses associated all NetworkInterfaces, but how do I distinguish them?? This is the output I am getting:

127.0.0.1
192.168.1.2
192.168.56.1
117.204.44.19

Source: (StackOverflow)

iPhone Data Usage Tracking/Monitoring

I've searched over this topic but found very few details which were helpful. With these details I've tried to cook some code as follows.

Note: Please compare the details shared in this post with other posts before marking this as DUPLICATE, and not just by the subject.

- (NSArray *)getDataCountersForType:(int)type {
    BOOL success;
    struct ifaddrs *addrs = nil;
    const struct ifaddrs *cursor = nil;
    const struct sockaddr_dl *dlAddr = nil;
    const struct if_data *networkStatisc = nil; 

    int dataSent = 0;
    int dataReceived = 0;

    success = getifaddrs(&addrs) == 0;
    if (success) {
        cursor = addrs;
        while (cursor != NULL) {
            if (cursor->ifa_addr->sa_family == AF_LINK) {
                dlAddr = (const struct sockaddr_dl *) cursor->ifa_addr;
                networkStatisc = (const struct if_data *) cursor->ifa_data;

                if (type == WiFi) {
                    dataSent += networkStatisc->ifi_opackets;
                    dataReceived += networkStatisc->ifi_ipackets;   
                }
                else if (type == WWAN) {
                    dataSent += networkStatisc->ifi_obytes;
                    dataReceived += networkStatisc->ifi_ibytes; 
                }
            }
            cursor = cursor->ifa_next;
        }
        freeifaddrs(addrs);
    }       
    return [NSArray arrayWithObjects:[NSNumber numberWithInt:dataSent], [NSNumber numberWithInt:dataReceived], nil];    
}

This code collects information of internet usage of an iPhone device (and not my application alone).

Now, if I use internet through WiFi or through 3G, I get the the data (bytes) only in ifi_obytes (sent) and ifi_ibytes (received) but I think I should get WiFi usage in ifi_opackets and ifi_ipackets.

Also wanted to add that if I'm connected to a WiFi network, but am not using internet, I still get value added to ifi_obytes and ifi_ibytes.

May be I'm wrong in the implementation or understanding. Need someone to help me out.


Edit: Instead of AF_LINK I tried AF_INET (sockaddr_in instead of sockaddr_dl). This crashes the application.


Source: (StackOverflow)

Send message to specific client with socket.io and node.js

I'm working with socket.io and node.js and until now it seems pretty good, but I don't know how to send a message from the server to an specific client, something like this:

client.send(message, receiverSessionId)

But neither the .send() nor the .broadcast() methods seem to supply my need.

What I have found as a possible solution, is that the .broadcast() method accepts as a second parameter an array of SessionIds to which not send the message, so I could pass an array with all the SessionIds connected at that moment to the server, except the one I wish send the message, but I feel there must be a better solution.

Any ideas?


Source: (StackOverflow)

How to fix java.net.SocketException: Broken pipe?

I am using apache commons http client to call url using post method to post the parameters and getting the below error rarely. When I explore the reason, didnt get the exact reason for the cause. Can anyone suggest a way to fix this?

java.net.SocketException: Broken pipe
        at java.net.SocketOutputStream.socketWrite0(Native Method)
        at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
        at java.net.SocketOutputStream.write(SocketOutputStream.java:136)
        at java.io.BufferedOutputStream.write(BufferedOutputStream.java:105)
        at java.io.FilterOutputStream.write(FilterOutputStream.java:80)
        at org.apache.commons.httpclient.methods.ByteArrayRequestEntity.writeRequest(ByteArrayRequestEntity.java:90)
        at org.apache.commons.httpclient.methods.EntityEnclosingMethod.writeRequestBody(EntityEnclosingMethod.java:499)
        at org.apache.commons.httpclient.HttpMethodBase.writeRequest(HttpMethodBase.java:2114)
        at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:1096)
        at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:398)

Source: (StackOverflow)

How to use the C socket API in C++ on z/OS

I've been having issues getting the C sockets API to work properly in C++. Specifically, although I am including sys/socket.h, I still get compile time errors telling me that AF_INET is not defined. Am I missing something obvious, or could this be related to the fact that I'm doing this coding on z/OS and my problems are much more complicated?


Update: Upon further investigation, I discovered that there is an #ifdef that I'm hitting. Apparently z/OS isn't happy unless I define which "type" of sockets I'm using with:

#define _OE_SOCKETS

Now, I personally have no idea what this _OE_SOCKETS is actually for, so if any z/OS sockets programmers are out there (all 3 of you), perhaps you could give me a rundown of how this all works?


Source: (StackOverflow)