TCP socket programming instance 1-Client

Source: Internet
Author: User

/*
* Tcpclient. c
*/
# Include <sys/types. h>
# Include <sys/socket. h>
# Include <stdio. h>
# Include <stdlib. h>
# Include <errno. h>
# Include <string. h>
# Include <unistd. h>
# Include <netinet/in. h>
# Include <netdb. h>
# Define servport 1888
# Define maxdatasize 30
 
Int main (INT argc, char * argv [])
{
Int sockfd, sendbytes;
Char Buf [maxdatasize];
Struct hostent * Host;
Struct sockaddr_in serv_addr;
If (argc <2 ){
Fprintf (stderr, "Please enter the server's hostname! \ N ");
Exit (1 );
}
/* Get host */
If (host = gethostbyname (argv [1]) = NULL ){
Perror ("gethostbyname ");
Exit (1 );
}
/* Create socket */
If (sockfd = socket (af_inet, sock_stream, 0) =-1 ){
Perror ("socket ");
Exit (1 );
}
 
/* Set sockaddr_in parameters */
Serv_addr.sin_family = af_inet; // address cluster
Serv_addr.sin_port = htons (servport); // port number
Serv_addr.sin_addr = * (struct in_addr *) Host-> h_addr); // sever IP Address
Bzero (& (serv_addr.sin_zero), 8); // fill in 0 to keep the same size as struct sockaddr
 
/* Connect to sever */
If (connect (sockfd, (struct sockaddr *) & serv_addr, sizeof (struct sockaddr) =-1 ){
Perror ("Connect ");
Exit (1 );
}
 
/* Send MSG to server */
If (sendbytes = Send (sockfd, "hello", 5, 0) =-1 ){
Perror ("send ");
Exit (1 );
}
Close (sockfd );
}

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.