Home > OS >  Written in C Windows and Ubuntu problems of TCP communications program
Written in C Windows and Ubuntu problems of TCP communications program

Time:05-22

The following is a Linux as client program
# include & lt; stdio.h>
# include & lt; String. H>
# include & lt; Stdlib. H>
# include & lt; Unistd. H>
# include & lt; ARPA/inet. H>
# include & lt; Sys/socket. H>
# include
Int main () {
//create a socket
Int the sock=socket (AF_INET SOCK_STREAM, 0).

//to the server IP and port (specific) initiating
Struct sockaddr_in serv_addr.
Memset (& amp; Serv_addr, 0, sizeof (serv_addr));//every byte 0 populate
Serv_addr. Sin_family=AF_INET;//using IPv4 address
Serv_addr. The sin_addr. S_addr=inet_addr (" 127.0.0.1 ");//the IP address of the specific
Serv_addr. The sin_port=htons (6000);//port
Int err=connect (the sock, (struct sockaddr *) & amp; Serv_addr, sizeof (serv_addr));
If (err==1)
{
Printf (" error "\ n");
}
The else
{
Printf (" nice \ n ");
}



//read the data back to the
Char readbuffer [100].
Read (the sock, readbuffer, sizeof (readbuffer) - 1);
Printf (" the Message form the server: % s \ n ", readbuffer);

//send server
Char send []="you too";
Write (sock, send, sizeof (send));
//close the socket
Close (sock);

return 0;
}

Windows as server
# include & lt; stdio.h>
# include & lt; Winsock2. H>
# pragma comment (lib, "ws2_32. Lib")//need to load ws2_32. DLL Windows network programming library

Int main () {
//initialize the DLL library
WSADATA WSADATA;
WSAStartup (MAKEWORD (2, 2), & amp; WsaData);

//create a socket
SOCKET servSock=SOCKET (AF_INET SOCK_STREAM, IPPROTO_TCP);

//bind socket
Sockaddr_in sockAddr.
Memset (& amp; SockAddr, 0, sizeof (sockAddr));//every byte 0 populate
SockAddr. Sin_family=PF_INET;//using IPv4 address
SockAddr. Sin_addr. S_addr=inet_addr (" 127.0.0.1 ");//the IP address of the specific
SockAddr. Sin_port=htons (6000);//port
Bind (servSock, (SOCKADDR *) & amp; SockAddr, sizeof (sockAddr));

//into the listening state
Listen (servSock, 20);

//receiving client requests
SOCKADDR clntAddr;
Int nSize=sizeof (SOCKADDR);
The SOCKET clntSock=accept (servSock, (SOCKADDR *) & amp; ClntAddr, & amp; NSize);

//to send data to the client
Char * STR="Hello World!" ;
Send (clntSock, STR, strlen (STR) + sizeof (char), NULL);

Char re [100].
Recv (clntSock, re, sizeof (re), NULL);

//close the socket
Closesocket (clntSock);
Closesocket (servSock);

//terminate the use of DLL
WSACleanup ();

return 0;
}
Start Windows server first and then start the Ubuntu client run results are as follows:


Excuse me, how to solve the connection fails this problem?

CodePudding user response:

Have found what is the problem,
  • Related