40
36

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

UnityでUDPを送信してみる

Last updated at Posted at 2014-11-04

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

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

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

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

attach.png

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

play.png

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

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
40
36
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
40
36

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?