Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

怎么设置listen的ip地址?

`

{ok, Listen} = gen_tcp:listen(2345, [binary, {packet, 4}, {reuseaddr, true}, {active, true}]),
% {ok, Listen} = gen_tcp:listen(2345, [binary, {packet, 4}, {"36.7.227.13", true}, {active, true}]),

`

第一行在本地localhost上监听,我想指定ip地址,第二行错了,应该是不能直接用字符串,而是用4字节的ip地址。该怎么写这行程序?


网上找了一些程序,大概如下,但是运行提示错了,信息很简单,只说12,15行之前错了,也就是Ip_to_integer和Integer_to_ip之前错了。

#!/usr/bin/env escript

main(_) ->
    % ok 是一个atom类型,在ErLang里,atom只能用于比较是否相同, 内部可能使用整数来代表某个atom
    {ok, Listen} = gen_tcp:listen(2345, [binary, {packet, 4}, {reuseaddr, true}, {active, true}]),
    % {ok, Listen} = gen_tcp:listen(2345, [binary, {packet, 4}, {Ip_to_integer([36,7,227,13]), true}, {active, true}]),
    {ok, Socket} = gen_tcp:accept(Listen),
    {ok,{IP_Address,Port}} = inet:peername(Socket),
    io:format("[~p][~p] ~n", [IP_Address, Port]),
    gen_tcp:close(Socket).

Ip_to_integer([A,B,C,D]) ->
    (A*16777216)+(B*65536)+(C*256)+ D.

Integer_to_ip=fun(Ip)-> {Ip bsr 24, (Ip band 16711680) bsr 16, (Ip band 65280) bsr 8, Ip band 255} end.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
{ok, Listen} = gen_tcp:listen(2345, [binary, {packet, 4}, {ip,{127,0,0,1}}, {active, true}]).

在inet.erl line 801


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...