Winsock Service Program

Source: Internet
Author: User

# Include <winsock2.h>
# Include <stdio. h>

Int main (INT argc, char ** argv)
{
Wsadata;
Char hostname [256];
Hostent * hostent;
Protoent * protoent;
In_addr ** ADDR;
Char * ipaddr;
Socket socket;
Sockaddr_in sin;
Socket acceptsocket;
 
// Initialize Winsock
If (wsastartup (makeword (2, 2), & wsadata ))
{
Printf ("init Winsock failed! \ N ");
Return 1;
}

// Obtain the Host Name
Gethostname (hostname, 256 );
Printf ("% s \ n", hostname );

// Obtain host information
Hostent = gethostbyname (hostname );
Printf ("% s \ n", hostent-> h_name );
 
// List Host IP addresses
ADDR = (in_addr **) hostent-> h_addr_list;
While (* ADDR)
{
Ipaddr = inet_ntoa (** ADDR );
Printf ("% s \ n", ipaddr );
ADDR ++;
}

 
// Create a socket
 
Protoent = getprotobyname ("TCP ");
 
Socket = socket (af_inet, sock_stream, protoent-> p_proto );

If (socket <0)
{
Printf ("socket error! ");
Return 2;
}

 
// Bind a socket
Sin. sin_port = htons (23 );
Sin. sin_family = af_inet;
Sin. sin_addr.s_addr = 0;

If (BIND (socket, (sockaddr *) & sin, sizeof (SIN )))
{
Printf ("% s \ n", "socket error! ");
Return 3;
}

// Listen for requests
If (Listen (socket, 1 ))
{
Printf ("% s", "socket error! ");
Return 4;
}
 
//
While (1)
{
Acceptsocket = socket_error;
While (acceptsocket = socket_error)
{
Acceptsocket = accept (socket, (sockaddr *) & sin, null );
}
Printf ("Client Connected. \ n ");
Break;
}

Char MSG [] = "\ r \ n = connected! = \ R \ n ";

Printf ("% d \ n", send (acceptsocket, MSG, strlen (MSG), 0 ));

// Disable the socket sending and receiving function
Shutdown (acceptsocket, 0 );

Closesocket (acceptsocket );
Closesocket (socket );

// Cancel the blocked socket
If (wsaisblocking () wsacancelblockingcall ();
 
// Release Winsock Resources
Wsacleanup ();
 
Return 0;
}

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.