Socket programming sockets Windows Platform C language implementation

Source: Internet
Author: User

"Compiling environment": Visual Studio 2013

#include <stdio.h> #include <stdlib.h> #include <winsock2.h> #pragma comment (lib, "Ws2_32.lib") const int back_log = 5;int main (int argc, char * argv[]) {//Initialize socket wsadata wsadata;int ret = WSAStartup (Makeword (2, 4), &wsada TA); if (0! = ret) {fputs ("WSAStartup error\n", stderr); return 1;} Create socket Socket sock = socket (af_inet, Sock_stream, ipproto_tcp), if (Invalid_socket = = sock) {fputs ("socket () error\n", STD ERR); WSACleanup (); return 1;} Bind socket sockaddr_in sockaddr;memset (&sockaddr,0,sizeof (sockaddr_in)); sockaddr.sin_family = af_inet;//protocol cluster, general use AF _inet represents the TCP/IP protocol sockaddr.sin_addr. S_un. S_ADDR = htonl (addr_any);//indicates IP address Sockaddr.sin_port = htons (7);//indicates port ret = bind (sock, (sockaddr*) &sockaddr, sizeof ( SOCKADDR)), if (socket_error = = ret) {fputs ("bind () error\n", stderr); closesocket (sock); WSACleanup (); return 1;} Listen SOCKET RET = Listen (sock, Back_log), if (socket_error = = ret) {fputs ("Listen () error\n", stderr); closesocket (sock); WSACleanup (); return 1;} Receive socket sockaddr_in Clientaddr;int SZclientaddr = sizeof (CLIENTADDR); SOCKET Clientsock = Accept (sock, (sockaddr*) &clientaddr, &szclientaddr); if (Invalid_socket = = Clientsock) { Fputs ("Accept () error\n", stderr); closesocket (sock); WSACleanup (); return 1;} Send and receive Data Tchar Buff[256];memset (&buff,0,sizeof (Buff)); recv (Buff), 0); Sock,buff,sizeof () returns the number of bytes read in//RECV Buff2[] = "quit\n"; Send (sock, buff2, sizeof (BUFF2), 0);//Success returns the number of characters actually transferred//recycle resource closesocket (sock); Closesocket ( Clientsock); WSACleanup (); return 0;}


Socket programming sockets Windows Platform C language implementation

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.