-1

我无法在 Windows(C 语言)上使用绑定方法。出色地。我的代码应该做以下事情:

  1. 从用户那里获取 2 个地址:一个必须是本地计算机的 IP 地址,另一个必须是远程地址(例如 google 地址)。
  2. 我正在编写的应用程序将绑定到本地地址
  3. 应用程序将连接到第二个地址。

我从网上得到了一些代码。您可以查看我在评论中咨询过的所有来源。

This application will only accepts a string from the client (which specifies the local
address which the application will bind), then, the app will connect to a remote service
google, youtube or whatever. The main purpose that this app serves is to know if, when
 binded to a local address, the operative system (in this case Windows Based system) gives priority to:
- SA/DA rule
- Forwarding table




SOURCES:

http://stackoverflow.com/questions/2065495/using-a-specific-network-interface-for-a-socket-in-windows
http://stackoverflow.com/questions/2605182/when-binding-a-client-tcp-socket-to-a-specific-local-port-with-winsock-so-reuse
http://www.delta-search.com/?q=error+on+binding+to+local+address%2Cwindows&s=web&as=0&rlz=0&babsrc=HP_ss
http://social.msdn.microsoft.com/Forums/zh/vcgeneral/thread/763a00ab-0e7f-44c6-9794-840fc6cb2e07
http://www.delta-search.com/?q=add+ws2_32.lib+visual+studio+2010&babsrc=HP_ss&s=web&rlz=0&as=3&ac=0%2C331
http://stackoverflow.com/questions/5220309/why-am-i-getting-linker-errors-for-ws2-32-dll-in-my-c-program
http://msdn.microsoft.com/en-US/windows/desktop/aa904949
http://msdn.microsoft.com/en-us/library/windows/desktop/ms737550(v=vs.85).aspx



#pragma once
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
#include <Ws2tcpip.h>
#include <stdio.h>


void Abort(char *msg);

void main(int argc,char*argv[]){

    int ret, fd;
    struct sockaddr_in sa_dst;
    struct sockaddr_in sa_loc;

    if(argc < 3)
        Abort("Syntax: SourceIpAddress(to bind) DestinationIpAddress(to connect)");


    fd = socket(AF_INET, SOCK_STREAM, 0);

    // Local
    memset(&sa_loc, 0, sizeof(struct sockaddr_in));
    sa_loc.sin_family = AF_INET;
    sa_loc.sin_port = htons(0);
    sa_loc.sin_addr.s_addr = inet_addr(argv[1]);

    if((ret = bind(fd, (struct sockaddr *)&sa_loc, sizeof(struct sockaddr))) < 0)
        Abort("Binding to local address");


    // Remote
    memset(&sa_dst, 0, sizeof(struct sockaddr_in));
    sa_dst.sin_family = AF_INET;
    sa_dst.sin_port = htons(80);
    sa_dst.sin_addr.s_addr = inet_addr(argv[2]); // google :)

    if((ret = connect(fd, (struct sockaddr *)&sa_dst, sizeof(struct sockaddr))) < 0)
        Abort("Connect to remote address");

    printf("\n\nConnection Successfully made!!\n\n");    }

void Abort(char *msg){
fprintf(stderr,"\n\n<ERROR>: <%s>\n",msg);
perror("\n\nExiting...");
exit(EXIT_FAILURE);       }

问题是绑定返回-1。我已经测试过了。

谁可以帮我这个事?

提前致谢

4

1 回答 1

1

当 Winsock 函数失败时,您可以调用WSAGetLastError()以找出原因。

在这种情况下,您没有调用WSAStartup(),因此socket()失败并WSANOTINITIALISED出现您忽略的错误,因此您最终将无效套接字传递给bind().

于 2013-03-02T02:19:42.837 回答