C language wrote a socket server side, suitable for Windows and Linux, with GCC compiled run through

Source: Internet
Author: User

///////////////////////////////////////////////////////////////////////////////
/*
Gcc-wall-o S1 s1.c-lws2_32
*/
///////////////////////////////////////////////////////////////////////////////

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>

#define _WIN32_WINNT 0x501
#define PORT 4000
#define IP_Address "127.0.0.1"
///////////////////////////////////////////////////////////////////////////////
Sk

#ifdef _WIN32_WINNT
#include <ws2tcpip.h>
#include <winsock2.h>
Wsadata Ws;
#else
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/un.h>
#include <netdb.h>
#endif

///////////////////////////////////////////////////////////////////////////////
Sk

void Connect_inet_socket (int *psockfd, const char* host, int port);

#ifdef _WIN32_WINNT
void Connect_windows_socket (int *psockfd, const char* pathname);
#else
void Connect_unix_socket (int *psockfd, const char* pathname);
#endif

void Writebuffer_socket (int sockfd, const void *data, int len);
void Readbuffer_socket (int sockfd, void *data, int len);
void Shutdown_socket (int sockfd);

///////////////////////////////////////////////////////////////////////////////
Sk
/* Access to sockets needs to is done with a wrapper function ' Connect_socket '
And it is substituted by ' connect_windows_socket ' or by ' connect_unix_socket '
(Depends on a state of the macro _win32) during preprocessing phase of
The compilation.
For portability ' connect_windows_socket ' and ' connect_unix_socket ' shouldn ' t
be used directly and the wrapper function ' Connect_socket ' must be used instead.
*/

#ifdef _WIN32_WINNT
#define Connect_socket Connect_windows_socket
#else
#define Connect_socket Connect_unix_socket
#endif

int Socket_desc;
struct SOCKADDR_IN server;

///////////////////////////////////////////////////////////////////////////////
/* Opens an Internet socket.

Note that Fortran passes a extra argument for the string length,
It's ignored here for C compatibility.

Args:
Psockfd:the ID of the socket that would be created.
Port:the port number for the socket is created. Low numbers is
Often reserved for important channels, so use of numbers of 4
or more digits is recommended.
Host:the name of the host server.
*/

void Connect_inet_socket (int *psockfd, const char* host, int port)
{
int SOCKFD, Ai_err;

Creates an internet socket

Fetches information on the host
struct addrinfo hints, *res;
Char service[256];

memset (&hints, 0, sizeof (hints));
Hints.ai_socktype = Sock_stream;
hints.ai_family = Af_unspec;
Hints.ai_flags = ai_passive;

sprintf (Service, "%d", port); Convert the port number to a string
Ai_err = getaddrinfo (host, service, &hints, &res);
if (ai_err!=0) {
printf ("Error Code:%i\n", Ai_err);
Perror ("Error fetching host data. Wrong host name? ");
Exit (-1);
//}

Creates socket
SOCKFD = socket (res->ai_family, Res->ai_socktype, Res->ai_protocol);
SOCKFD = socket (af_inet, sock_stream, ipproto_tcp);
if (SOCKFD < 0) {
Perror ("Error opening socket");
Exit (-1);
}
Else
{
printf ("Creates socket:%d\n", SOCKFD);
}

Makes connection
if (Connect (SOCKFD, res->ai_addr, Res->ai_addrlen) < 0) {
Perror ("Error opening INET socket:wrong port or Server unreachable");
Exit (-1);
}
Freeaddrinfo (RES);

*PSOCKFD = SOCKFD;
}

///////////////////////////////////////////////////////////////////////////////
Sk
/* Opens a socket.

Note that Fortran passes a extra argument for the string length,
It's ignored here for C compatibility.

Args:
Psockfd:the ID of the socket that would be created.
Pathname:the name of the file to use for Sun_path.
*/

#ifdef _WIN32_WINNT

void Connect_windows_socket (int *psockfd, const char* pathname)
{
Required functionality for Windows

// ...
}

#else

void Connect_unix_socket (int *psockfd, const char* pathname)
{
Required functionality for Unix

int SOCKFD, Ai_err;

struct sockaddr_in serv_addr;

printf ("Connecting to:%s:\n", pathname);

Fills up details of the socket addres
memset (&serv_addr, 0, sizeof (SERV_ADDR));
serv_addr.sun_family = Af_unix;
/* Beware of buffer over runs
UNIX Network programming by Richard Stevens mentions
The use of sizeof () is OK, but see
Http://mail-index.netbsd.org/tech-net/2006/10/11/0008.html
*/
if ((int) strlen (pathname) > sizeof (Serv_addr.sun_path)) {
Perror ("Error opening UNIX socket:pathname too long\n");
Exit (-1);
} else {
strcpy (Serv_addr.sun_path, pathname);
}
Creates a UNIX socket

Creates the socket
SOCKFD = socket (Af_unix, sock_stream, 0);

Connects
if (Connect (SOCKFD, (struct sockaddr *) &serv_addr, sizeof (SERV_ADDR)) < 0) {
Perror ("Error opening UNIX Socket:path unavailable, or already existing");
Exit (-1);
}
*PSOCKFD = SOCKFD;
}

#endif

///////////////////////////////////////////////////////////////////////////////
/* writes to a socket.

Args:
Sockfd:the ID of the socket that is written to.
Data:the data to is written to the socket.
Len:the length of the data in bytes.
*/

void Writebuffer_socket (int sockfd, const void *data, int len)
{
int n;

n = Write (SOCKFD, (char *) data, Len);
if (n < 0) {
Perror ("Error writing to Socket:server have quit or connection broke");
Exit (-1);
}
}

///////////////////////////////////////////////////////////////////////////////
/* Reads from a socket.

Args:
Sockfd:the ID of the socket that would be read from.
Data:the storage array for data read from the socket.
Len:the length of the data in bytes.
*/

void Readbuffer_socket (int sockfd, void *data, int len)
{
int n, nr;
Char *pdata;

pdata = (char *) data;
n = NR = Read (SOCKFD, pdata, Len);

while (nr > 0 && n < len) {
NR = Read (SOCKFD, & (Pdata[n)), len-n);
n + = nr;
}
if (n = = 0) {
Perror ("Error reading from Socket:server have quit or connection broke");
Exit (-1);
}
}

///////////////////////////////////////////////////////////////////////////////
/* shuts down the socket.
*/

void Shutdown_socket (int sockfd)
{
Shutdown (SOCKFD, 2);
Close (SOCKFD);
}

DWORD WINAPI clientthread (LPVOID lpparameter)
{
Socket Cientsocket = (socket) Lpparameter;
int Ret = 0;
Char recvbuffer[1024];
Char message[] = "Hello Master haku!";

while (1)
{
memset (Recvbuffer, 0x00, sizeof (Recvbuffer));
Ret = recv (Cientsocket, Recvbuffer, 1024, 0);
if (Ret = = 0 | | Ret = = socket_error)
{
printf ("Client exit!\n");
Break
}
printf ("Received customer information for%s\n", Recvbuffer);
Ret = Send (Cientsocket, "Hello World", (int.) strlen ("Hello World"), 0);
Ret = Write (Cientsocket, "Hello World", sizeof ("Hello World"));
Write (cientsocket, message, sizeof (message));
Send (Cientsocket, "Hello World", strlen ("Hello World"), 0);
if (Ret = = 0 | | Ret = = socket_error)
//{
printf ("Return to client%s\n", message);
Break
//}
}

return 0;
}


int main (void)
{
int *socket_desc;
SOCKET ServerSocket, Clientsocket;
struct sockaddr_in localaddr, clientaddr;
int Ret = 0;
int addrlen = 0;
HANDLE hthread = NULL;
Char Sendbuffer[max_path];
Char message[30] = "Hello Master haku!";

#ifdef _WIN32_WINNT
Init Windows Socket
if (WSAStartup (Makeword (2,2), &ws)! = 0)
{
printf ("Init Windows Socket Failed");
return-1;
}
#endif

Connect_inet_socket (Socket_desc, "http://blog.csdn.net", 80);
Create socket
ServerSocket = socket (af_inet, sock_stream, ipproto_tcp);
if (Socket_desc = =-1)
{
printf ("Could not create socket");
}

localaddr.sin_family = af_inet;
LOCALADDR.SIN_ADDR.S_ADDR = inet_addr (ip_address);
Localaddr.sin_port = htons (port);
memset (Localaddr.sin_zero, 0x00, 8);

Bind Socket
Ret = Bind (ServerSocket, (struct sockaddr*) &localaddr, sizeof (LOCALADDR));
if (Ret! = 0)
{
printf ("Bind Socket Failed");
return-1;
}
Listen

Ret = Listen (ServerSocket, 10);
if (Ret! = 0)
{
printf ("Listen Socket Failed");
return-1;
}

printf ("Server has started \ n");

while (1)
{
Addrlen = sizeof (CLIENTADDR);
Clientsocket = Accept (ServerSocket, (struct sockaddr*) &clientaddr, &addrlen);
if (Clientsocket = = Invalid_socket)
{
printf ("Accept Failed");
Break
}

Write (clientsocket, message, sizeof (message));
Send (clientsocket, message, strlen (message), 0);

printf ("Client connection \ n");

Hthread = CreateThread (null, 0, Clientthread, (LPVOID) clientsocket, 0, NULL);
if (hthread = = NULL)
{
printf ("Create Thread failed!");
Break
}

CloseHandle (Hthread);
}

Closesocket (ServerSocket);
Closesocket (Clientsocket);
WSACleanup ();

return 0;
}

C language wrote a socket server side, suitable for Windows and Linux, with GCC compiled run through

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.