Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Unix Socket programming: TCP server

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/03 Report--

# include

# include

# include

# include

# include

# include

Int main (int argc,char * argv [])

{

Int serv_sock,clnt_sock

Char msg [] = "Hello SZT! ~"

Struct sockaddr_in serv_adr,clnt_adr

Socklen_t clnt_adr_sz

If (argc! = 2)

{

Printf ("Please enter the port number when running! ~\ n")

Exit (1)

}

Serv_sock = socket (PF_INET,SOCK_STREAM,0)

Memset (& serv_adr,0,sizeof (serv_adr))

Serv_adr.sin_family = AF_INET

Serv_adr.sin_addr.s_addr = htonl (INADDR_ANY)

Serv_adr.sin_port = htons (atoi (argv [1]))

Bind (serv_sock, (struct sockaddr *) & serv_adr,sizeof (serv_adr))

If (listen (serv_sock,5)! =-1)

{

Printf ("listen (); waiting for client connection, port:% s\ n", argv [1])

}

Clnt_adr_sz = sizeof (clnt_adr)

Clnt_sock = accept (serv_sock, (struct sockaddr *) & serv_adr,&clnt_adr_sz)

If (clnt_sock! =-1)

{

Printf ("accept (); client connected\ n")

}

Write (clnt_sock,msg,sizeof (msg))

Printf ("write (); data has been sent:% s\ n", msg)

Close (clnt_sock)

Close (serv_sock)

Return 0

}

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report