Function: The client sends a TCP packet, which the program accepts, converts the letter to uppercase, and sends it to the client
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
int port = 8000;
int main ()
{
struct sockaddr_in sin,cliaddr;
struct SOCKADDR_IN pin;
int sock_descriptor;
int temp_sock_descriptor;
int address_size;
Char buf[16384];
int I, Len;
Sock_descriptor = socket (af_inet, sock_stream, 0);//tcp
Sock_descriptor = socket (af_inet, SOCK_DGRAM, 0);//udp
if (Sock_descriptor = =-1) {
Perror ("Call to Socket");
Exit (1);
}
Bzero (&sin, sizeof (sin));
sin.sin_family = af_inet;
Sin.sin_addr.s_addr = inaddr_any;//automatically fills in the native IP address
Sin.sin_port = htons (port);
if (Bind (Sock_descriptor, (struct sockaddr *) &sin, sizeof (sin)) = =-1) {
Perror ("Call to bind");
Exit (1);
}
if (Listen (sock_descriptor, 20) = =-1) {
Perror ("Call to listen");
Exit (1);
}
printf ("Accepting connections ... \ n");
int addr_len=sizeof (struct sockaddr_in);
while (1)
{
Temp_sock_descriptor = Accept (Sock_descriptor, (struct sockaddr *) &pin,&address_size);
if (Temp_sock_descriptor = =-1) {
Perror ("Call to accept");
Exit (1);
}
if (recv (Temp_sock_descriptor, buf, 16384, 0) = =-1) {
Perror ("Call to Recv");
Exit (1);
}
printf ("Received from client:%s\n", buf);
For this server example, we just convert the
Characters to upper case:
Len = strlen (BUF);
for (i=0; i<len; i++) Buf[i] = ToUpper (Buf[i]);
ToUpper converts the character C to uppercase English letters
if (Send (Temp_sock_descriptor, buf, len, 0) = =-1) {
Perror ("Call to send");
Exit (1);
}
Close (Temp_sock_descriptor);
}
}
From http://blog.sina.com.cn/s/blog_79d1978a0100q4p7.html
TCP Package server accepts programs