Windows Socket 编程, WIN32_LEAN_AND_MEAN 的用法

7 篇文章 0 订阅

一、基本Socket 调用

原文地址:Getting Started with Winsock

注意关于windows.h 与 winsock2.h 一起使用时的问题:

The Winsock2.h header file internally includes core elements from theWindows.h header file, so there is not usually an #include line for theWindows.h header file in Winsock applications. If an #include line is needed for theWindows.h header file, this should be preceded with the #define WIN32_LEAN_AND_MEAN macro. For historical reasons, theWindows.h header defaults to including theWinsock.h header file for Windows Sockets 1.1. The declarations in theWinsock.h header file will conflict with the declarations in theWinsock2.h header file required by Windows Sockets 2.0. The WIN32_LEAN_AND_MEAN macro prevents theWinsock.h from being included by theWindows.h header. An example illustrating this is shown below.

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iphlpapi.h>
#include <stdio.h>

#pragma comment(lib, "Ws2_32.lib")

int main() {
  return 0;
}

二、高级调用及线程管理

1. 多线程

原文地址:C++ Socket Class for Windows 

A simple echo server:

#include "Socket.h"
#include <process.h>
#include <string>

unsigned __stdcall Answer(void* a) {
  Socket* s = (Socket*) a;

  while (1) {
    std::string r = s->ReceiveLine();
    if (r.empty()) break;
    s->SendLine(r);
  }

  delete s;

  return 0;
}

int main(int argc, char* argv[]) {
  SocketServer in(2000,5);

  while (1) {
    Socket* s=in.Accept();

    unsigned ret;
    _beginthreadex(0,0,Answer,(void*) s,0,&ret);
  }
 
  return 0;
}

2. 从已建立连接的socket 取得对方IP 地址

	SOCKET ClientSocket = accept(ListenSocket, NULL, NULL);
	sockaddr_in remoteName;
	int  remNameLen=sizeof(remoteName);
	memset((void *)& remoteName, 0, remNameLen);

	int iResult = getpeername(ClientSocket, (sockaddr *) & remoteName,& remNameLen);
	printf("Remote IP: %s\n", inet_ntoa(remoteName.sin_addr));





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值