windows下简单的网络套接字编程

1.文件传输

通过建立服务器客户端连接,进行文件传输。由客户端输入一个文件名,服务器搜素,查找成功后,向客户端传输数据。客户端接受在当前目录下创建文件。

// hdksjfkl.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include 
#include 
#include 
#include "iostream"
#define  MAXSTRINGSIZE 9000
using namespace std;
#pragma  comment (lib,"ws2_32.lib")

//获取本机IP  
in_addr getHostName(void)   
{  
    char host_name[255];  
    //获取本地主机名称  
    if (gethostname(host_name, sizeof(host_name)) == SOCKET_ERROR) {  
        cout<<"Error %d when getting local host name."<h_addr_list[0], sizeof(struct in_addr));  
    return addr;   
}  


//启动服务器  
SOCKET StartServer(void)  
{  
    //创建套接字  
    SOCKET serverSocket;  
    if((serverSocket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))==INVALID_SOCKET){  
        cout<<"创建套接字失败!";  
        Sleep(3000);  
        exit(-1);  
    }  
    short port=1986;  
    struct sockaddr_in serverAddress;  
    //初始化指定的内存区域  
    memset(&serverAddress,0,sizeof(sockaddr_in));  
    serverAddress.sin_family=AF_INET;  
    serverAddress.sin_addr.S_un.S_addr = htonl(INADDR_ANY);  
    serverAddress.sin_port = htons(port);  
	
    //绑定  
    if(bind(serverSocket,(sockaddr*)&serverAddress,sizeof(serverAddress))==SOCKET_ERROR){  
        cout<<"套接字绑定到端口失败!端口:"<
以上是服务器段的代码。

// hdksjfklclien.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"  
#include   
#include   
#include   
#include "string.h"
using namespace std;  
#pragma comment(lib,"ws2_32.lib")  

//接收数据  
void Receive(SOCKET socket)  
{  
	
    char buf[2096];   
    int bytes;  
    if((bytes=recv(socket,buf,sizeof(buf),0))==SOCKET_ERROR){  
            printf("接收数据失败!\n");  
            exit(-1);  
        }  
        buf[bytes]='\0';  
        cout<>ipStr;  
	strcpy(ipStr,"127.0.0.1");
    unsigned long ip;  
    if((ip=inet_addr(ipStr))==INADDR_NONE){  
        cout<<"不合法的IP地址:";  
        Sleep(3000);  
        exit(-1);  
    }  
    return ip;  
}  
//发送数据 
 char path[80] = {'0'};
void SendMsg(SOCKET &sock)  
{  
	
	printf("请输入要下载的文件名\n");
	scanf("%s",path);
	printf("%d\n",strlen(path));
        if(send(sock,path,strlen(path)+1,0)==SOCKET_ERROR)
		{  
            cout<<"发送数据失败!";  
            exit(-1);  
        }   
		cout<<"发送数据是"<

以上是客户端的代码。



你可能感兴趣的:(计算机网络编程,C语言)