TCP Packet Server Accept program

Source: Internet
Author: User
Tags sin

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

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.