Client-server program for sockets

Source: Internet
Author: User
Tags socket error time and date htons

Client program:

Returns the current time and date through the server.

#include "Unp.h"
#include "My_err.h"
int main (int argc, char** argv)
{
int SOCKFD, n;
Char Recvline[maxline + 1];
struct sockaddr_in servaddr;
if (argc! = 2)
Err_quit ("usage:a.out<ipaddress>");
if ((SOCKFD = socket (af_inet, sock_stream, 0)) < 0)
Err_sys ("socket error");
Bzero (&servaddr, sizeof (SERVADDR));
servaddr.sin_family = af_inet;
Servaddr.sin_port = htons (13);
if (Inet_pton (Af_inet, argv[1], &servaddr.sin_addr) <= 0)
Err_quit ("Inet_pton error for%s", argv[1]);
if (Connect (SOCKFD, (sa*) &servaddr, sizeof (SERVADDR)) < 0)
Err_sys ("Connect error");
while ((n = Read (SOCKFD, Recvline, MAXLINE)) > 0)
{
Recvline[n] = 0;
if (fputs (recvline, stdout) = = EOF)
Err_sys ("fputs error");


Server-side programs:

Obtain the IP and port number of the client side. Inet_ntop converts the 32-bit IP address in the socket address structure to a dotted-decimal ASCII string, calling Nthos to convert the 16-bit port number from the network byte order to the host byte order.

int main (int argc, char** argv)
{
int LISTENFD, CONNFD;
Socklen_t Len;
struct sockaddr_in servaddr, cliaddr;
Char Buff[maxline];
teme_t ticks;
LISTENFD = socket (af_inet, sock_stream, 0);
Bzero (&servaddr, sizeof (SERVADDR));
servaddr.sin_family = af_inet;
SERVADDR.SIN_ADDR.S_ADDR = htonl (Inaddr_any);
Servaddr.sin_port = htons (13);
Bind (LISTENFD, (sa*) &servaddr, sizeof (SERVADDR));
Listen (LISTENFD, Listenq);
for (;;)
{
len = sizeof (CLIADDR);
CONNFD = Accept (LISTENFD, (sa*) &cliaddr, &len);
printf ("Connection from%s,port%d \ n", Inet_ntop (af_inet, &cliaddr.sin_addr, buff, sizeof (buff)), Ntohs ( Cliaddr.sin_port));
Ticks = time (NULL);
snprintf (buff, sizeof), "%.24s\r\n", CTime (&ticks));
Crite (CONNFD, Buff, strlen (buff));
Close (CONNFD);


}
}




Client-server program for sockets

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.