Search code examples
javasocketsosx-server

Port binding on macos


I used ServerSocket in java to check whether the mysql is running or not . If it's not running I prompted the user to please run your mysql server . But , Some of my users complained we got error message although the mysql is running . It only happens in macos . What I find is .

Java Code :

public static boolean isPortFree(int port)
{
    if(port <= 0)
    {
        return false;
    }
    ServerSocket sock = null;
    try
    {
        String bindAddress = System.getProperty("bindaddress", "127.0.0.1");
        sock = new ServerSocket(port,0,InetAddress.getByName(bindAddress));
    }
    catch(Exception ex)
    {
        return false;
    }
    finally
    {
        if (sock != null)
        {
            try
            {
                sock.close();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }
    return true;
}

If i set system property bindaddress to localhost it returns false same i set to 127.0.0.1 returns true . localhost , 127.0.0.1 is same why it behaves like this . It only occurs in macos . I think it's not a my.cnf bindaddress problem . Because I checked in command prompt with

 mysql -uroot -hlocalhost
 mysql -uroot -h127.0.0.1

both are works .

Netstat

MacOs

 tcp4       0      0  *.3306                 *.*                    LISTEN

Other Os

tcp        0      0 127.0.0.1:3306          0.0.0.0:*               LISTEN 

Is there any difference between tcp4 and tcp?

Any Idea why it happens ?


Solution

  • The two examples are effectively binding to different interfaces: INADDR_ANY does not prevent binds to specific adapters.

    It will work as expected if on OSX MySQL was configured exactly the same as your reported 'Other Os'.