peername(Socket) -> {ok, {Address, Port}} | {error, posix()}
Types:
Socket = socket()
Address = ip_address()
Port = integer() >= 0
Returns the address and port for the other end of a connection.
サンプル:
(サーバ)
1回だけクライアントと接続します。そのとき、接続元のクライアントのIPアドレスとポート番号を表示する。
(クライアント)
サーバへ1回だけ接続する。そのとき、サーバから受信したデータを表示する。サンプルでは「Hello」固定。
【サーバ】
-module( sock_srv_accept_info ).
-compile( export_all ).
server() ->
%% TCPクライアントからの接続要求を待てる状態
{ ok, LSock } = gen_tcp:listen( 12345, [ binary, { packet, 0 } ] ),
%% TCPクライアントからの接続要求を受け付ける
{ ok, ASock } = gen_tcp:accept( LSock ),
io:format( "accept:~p~n", [ inet:peername( ASock ) ] ), % 接続元のIPとポート番号表示
%% 送信
gen_tcp:send( ASock, "Hello" ),
%% TCPセッション終了
ok = gen_tcp:close( ASock ).
【クライアント】
-module( sock_client ).
-compile( export_all ).
client() ->
%% サーバ接続先
Server = "localhost",
%% サーバに接続
{ ok, Sock } = gen_tcp:connect( Server,
12345,
[ binary, { packet, 0} ] ),
%% サーバからデータ受信
%receive
% { tcp, Sock, Bin } ->
% io:format( "Client get:~p~n", [ binary:bin_to_list( Bin ) ] )
%end,
%% サーバからデータ受信
{ ok, Packet } = gen_tcp:recv( Sock, 0 ),
io:format( "time:~p~n", [ Packet ] ),
%% ソケットの終了
gen_tcp:close( Sock ).