LINUXSOCKET programming connecterror! : Socketoperationonnon-socket -- Linux general technology-Linux programming and kernel information. The following is a detailed description. // Server-side program
# Include
# Include
# Include
# Include
# Include
# Include
# Define SERVPORT 3333
# Define BACKLOG 10
Typedef struct sockaddr_in st;
Typedef struct sockaddr sd;
Int main ()
{
Int sockfd, clientfd;
St my_adder;
St client_adder;
Int sin_size;
If (sockfd = socket (AF_INET, SOCK_STREAM, 0) =-1)
{Perror ("socket default! ");
Exit (1 );
}
Printf ("% d", sockfd );
My_adder.sin_family = AF_INET;
My_adder.sin_port = htons (SERVPORT );
My_adder.sin_addr.s_addr = INADDR_ANY;
Bzero (& (my_adder.sin_zero), 8 );
If (bind (sockfd, (sd *) & my_adder, sizeof (sd) =-1)
{Perror ("bind error! ");
Exit (1 );
}
If (listen (sockfd, BACKLOG) =-1 ){
Perror ("linsten error ");
Exit (1 );
}
While (1 ){
Sin_size = sizeof (st );
If (clientfd = accept (sockfd, (sd *) & client_adder, & sin_size) =-1 ){
Perror ("accept error! ");
Continue;
}
Printf ("accept a meg from: % s \ n", inet_ntoa (client_adder.sin_addr ));
If (! Fork ()){
If (send (clientfd, "connect \ n", 26, 0) =-1)
Perror ("send error! ");
Close (clientfd );
Exit (0 );
}
Close (clientfd );
}
}
// Client program
# Include
# Include
# Include
# Include
# Include
# Include
# Include
Typedef struct sockaddr_in st;
Typedef struct sockaddr sd;
# Define SERVPORT 3333
# Define maxdatasalize 100
Int main (int argc, char * argv [])
{
Int sockfd, recvbytes;
Char buf [MAXDATASIZE];
Struct hostent * host;
St servaddr;
If (argc <2 ){
Fprintf (stdin, "please enter the sercer's hostname! \ N ");
Exit (1 );
}
If (host = gethostbyname (argv [1]) = NULL ){
Perror ("gethostbyname error! ");
Exit (1 );
}
If (sockfd = socket (AF_INET, SOCK_STREAM, 0) =-1 ){
Perror ("socket creat error! ");
Exit (1 );
}
Servaddr. sin_family = AF_INET;
Servaddr. sin_port = htons (SERVPORT );
Servaddr. sin_addr = * (struct in_addr *) host-> h_addr );
// Inet_ton (AF_INET, "127.0.0.3", & servaddr. sin_addr );
Bzero (& (servaddr. sin_zero), 8 );
If (connect (sockfd, (sd *) & servaddr, sizeof (sd) =-1 ){
Perror ("connect error! ");
Exit (1 );
}
If (recvbytes = recv (sockfd, buf, MAXDATASIZE, 0) =-1 ){
Perror ("receve error! ");
Exit (1 );
}
Buf [recvbytes] = '\ 0 ';
Printf ("receve: % s", buf );
Close (sockfd );
}
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.