UnityでUDPを送信してみる


UdpClient 使えば簡単。
とりあえずローカル環境で試したいので、ブロードキャストしてtcpdumpで見てみる。

ifconfig してブロードキャストアドレスを調べる。

$ ifconfig
...
    inet 192.168.0.0 netmask 0xffffff00 broadcast 192.168.0.255
...

Unity で下記スクリプトをメインカメラにでもくっつけて実行。

UDPClient.cs
using UnityEngine;
using System.Net.Sockets;
using System.Text;

public class UDPClient : MonoBehaviour
{
    // broadcast address
    public string host = "192.168.0.255";
    public int port = 3333;
    private UdpClient client;

    void Start ()
    {
        client = new UdpClient();
        client.Connect(host, port);
    }

    void Update ()
    {
    }

    void OnGUI()
    {
        if(GUI.Button (new Rect (10,10,100,40), "Send"))
        {
            byte[] dgram = Encoding.UTF8.GetBytes("hello!");
            client.Send(dgram, dgram.Length);
        }
    }

    void OnApplicationQuit()
    {
        client.Close();
    }
}

Unity で設定したポートを指定して、tcpdump する。

$ sudo tcpdump port 3333

ボタン押下して、こんな感じのが返ってきたら成功

tcpdump: data link type PKTAP
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on pktap, link-type PKTAP (Packet Tap), capture size 65535 bytes
18:33:46.175988 IP 192.168.0.0.53435 > 192.168.0.255.dec-notes: UDP, length 6