Connect C ++ unix server / socket to java windows client / socket

First, I would like to thank you for your time ...

I created a server socket in C ++ on my macbook and client / socket using Java on another machine that runs Windows XP. I pointed the port to 5000, but I cannot specify the correct host, and therefore I cannot establish a connection. When I created C ++ server / socket in windows xp using WinSock2, the connection was fine, since I used localhost ... any ideas ???

Thnx in advance

C ++ code


int main (int argc, const char ** argv) {

/* SOCKET VARIABLES */
int sock;
struct sockaddr_in server;
int mysock;
char buff[1024];
int rval;


/*CREATE SOCKET*/
sock =socket(AF_INET, SOCK_STREAM, 0);
if (sock<0) 
{
    perror("*FAILED TO CREATE SOCKET*");
    exit(1);
}

server.sin_family=AF_INET;
server.sin_addr.s_addr=INADDR_ANY;
server.sin_port=5000;

/*CALL BIND*/
if (bind(sock, (struct sockaddr *)&server, sizeof(server)))
{
    perror("BIND FAILED");
    exit(1);
}


/*LISTEN*/
listen(sock, 5);


/*ACCEPT*/
do{

    mysock= accept(sock, (struct sockaddr *) 0, 0);

    if (mysock==-1) 
    {

        perror ("ACCEPT FAILED");
    }
    else
    {
        memset(buff, 0, sizeof(buff));

        if ((rval=recv(mysock, buff, sizeof(buff), 0)) <0) {
            perror("READING STREAM MESSAGE ERROR");
        }
        else if(rval==0)
            printf("Ending connection");
        else
            printf("MSG: %s\n", buff);

        printf("GOT THE MESSAGE (rval = %d)\n", rval);

    }

    return 0;
}while (1) ;

Java code


import java.io .; import java.net .;

public class SOK_1_CLIENT {

public void run() throws Exception
{
    Socket SOCK =new Socket ("localhost",5000);
    PrintStream PS =new PrintStream(SOCK.getOutputStream());
    PS.println("HELLO TO SERVER FROM CLIENT");

    InputStreamReader IR =new InputStreamReader(SOCK.getInputStream());
    BufferedReader BR = new BufferedReader(IR);

    String MESSAGE =BR.readLine();
    System.out.println(MESSAGE + "java");
}

}


+4
source share
1 answer

java- IP- , , "localhost". Localhost loopback- , 127.0.0.1, , :

public void run() throws Exception
{
    String address = "address_of_machine_running_server";
    Socket SOCK =new Socket (address,5000);
    PrintStream PS =new PrintStream(SOCK.getOutputStream());
    PS.println("HELLO TO SERVER FROM CLIENT");

    InputStreamReader IR =new InputStreamReader(SOCK.getInputStream());
    BufferedReader BR = new BufferedReader(IR);

    String MESSAGE =BR.readLine();
    System.out.println(MESSAGE + "java");
}

, , .

  • IP- .
  • pinging () IP-, ,
  • , .
+1

Source: https://habr.com/ru/post/1523540/


All Articles